如何使用c#从服务器从特定文件夹获取FTP文件

问题描述 投票:0回答:1

我想使用c#通过FTP获取文件夹httpdocs / Demo /中最近30天的文件。

1。当用户在我们的网站上注册时,在使用FTP代码的服务器中,我正在使用当前日期创建文件夹名称。在演示文件夹中的每一天,都会创建一个新文件夹,其文件夹名称具有日期,如下所示

E.g: httpdocs/Demo/2Nov2017/
     httpdocs/Demo/3Nov2017/
     httpdocs/Demo/4Nov2017/
     httpdocs/Demo/5Nov2017/

2。在2Nov2017文件夹内将有多个文件,文件名将为user移动电话号码和日期时间的组合

  Eg:httpdocs/Demo/2Nov2017/34562ndnov2017file.txt

///这第三点我无法实现,请帮帮我

3。我需要检查httpdocs / Demo /中文件夹的最近30天使用日期通过FTP具有文件夹名称

4。我需要获取最近30天的文件,并应提供该文件的下载链接特定文件

c# ftp
1个回答
0
投票

这是FTP管理的类您必须在应用程序配置文件(App.Config)上添加以下配置键和值:App.Config

            <add key="FtpServer" value="yourFtpServer"/>
            <add key="FtpUserName" value="yourftpAccount"/>
            <add key="FtpPassword" value="yourFtpPassword"/>
            <add key="AllowRecursiveDirectory" value="0"/> boolean value   
            <add key="DeleteFileAfterDays" value="2"/>    

FTP类别

            using System.Configuration;
            using System.Collections.Generic;
            using System.IO;
            using System.Net;
            using System;
            using System.Text.RegularExpressions;
            using System.Globalization;

            namespace FTP_Demo
            {
                public class MyFTP
                {
                    string ServerAdress { get; set; }
                    string Login { get; set; }
                    string Password { get; set; }
                    bool Recurive { get; set; }
                    int DeleteFileAfterDays { get; set; }
                    public MyFTP(string serverAdress, string login, string password)
                    {
                        ServerAdress = serverAdress;
                        Login = login;
                        Password = password;
                        DeleteFileAfterDays = ToInt(ConfigurationManager.AppSettings.Get("DeleteFileAfterDays"));
                        Recurive = ToInt(ConfigurationManager.AppSettings.Get("AllowRecursiveDirectory"))==1;

                    }



                    public void DeleteFTPFile(string Path)
                    {
                        FtpWebRequest clsRequest = (System.Net.FtpWebRequest)WebRequest.Create("ftp://" + ServerAdress + Path);
                        clsRequest.Credentials = new System.Net.NetworkCredential(Login, Password);

                        clsRequest.Method = WebRequestMethods.Ftp.DeleteFile;

                        string result = string.Empty;
                        FtpWebResponse response = (FtpWebResponse)clsRequest.GetResponse();
                        long size = response.ContentLength;
                        Stream datastream = response.GetResponseStream();
                        StreamReader sr = new StreamReader(datastream);
                        result = sr.ReadToEnd();
                        sr.Close();
                        datastream.Close();
                        response.Close();
                       // Console.WriteLine("File Deleted: "+Path);
                    }



                    public int ToInt(string ss)
                    {
                        try
                        {
                            return Convert.ToInt32(ss);
                        }
                        catch (Exception e)
                        {
                            return 0;
                        }
                    }


                    /// <summary>
                    /// Delete expecific Diretory or recursive Diretory
                    /// </summary>
                    /// <param name="Path"></param>
                    public void DeleteFTPDirectory_new(string Path)
                    {
                        FtpWebRequest request = (System.Net.FtpWebRequest)WebRequest.Create("ftp://" + ServerAdress + Path);
                        request.Credentials = new System.Net.NetworkCredential(Login, Password);

                        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                        StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream());

                        string pattern = @"^(\d+-\d+-\d+\s+\d+:\d+(?:AM|PM))\s+(<DIR>|\d+)\s+(.+)$";
                        Regex regex = new Regex(pattern);
                        IFormatProvider culture = CultureInfo.GetCultureInfo("en-us");
                        while (!reader.EndOfStream)
                        {
                            string line = reader.ReadLine();
                            Match match = regex.Match(line);
                            DateTime modified =
                               DateTime.ParseExact(
                                   match.Groups[1].Value, "MM-dd-yy  hh:mmtt", culture, DateTimeStyles.None);
                            long size = (match.Groups[2].Value != "<DIR>") ? long.Parse(match.Groups[2].Value) : 0;
                            string name = match.Groups[3].Value;

                            if ((size > 0) && ((DateTime.Now - modified).TotalDays > DeleteFileAfterDays))
                            {
                                DeleteFTPFile(Path + "/" + name);
                                Console.WriteLine(string.Format(
                                "{0,-16} size = {1,9}  modified = {2} ------>was Deleted...",
                                Path + "/" + name, size, modified.ToString("yyyy-MM-dd HH:mm")));
                            }
                            else
                            if (size == 0 && name != "" && Recurive)
                                DeleteFTPDirectory_new(Path +"/"+name);

                        }
                    }
                }
            }

这是主应用代码

                using System;
            using System.Collections.Generic;
            using System.Configuration;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using System.Timers;

            namespace FTP_Demo
            {
                class Program
                {
                    static void Main(string[] args)
                    {

                        DeleteFtpFiles();
                        Console.ReadKey();

                    }

                    private static void DeleteFtpFiles()
                    {
                        try
                        {

                            string sFtpServer = ConfigurationManager.AppSettings.Get("FtpServer");
                            string sFtpUserName = ConfigurationManager.AppSettings.Get("FtpUserName");
                            string sFtpPassword = ConfigurationManager.AppSettings.Get("FtpPassword");
                            MyFTP ftp = new MyFTP(sFtpServer, sFtpUserName, sFtpPassword);

                            //ftp.DeleteFTPDirectory_new("/camera/frente");

                            string sDirectory = "";
                            Console.WriteLine(string.Format("************Started deleting directory: {0}****************", sDirectory));
                            ftp.DeleteFTPDirectory_new(sDirectory);
                            Console.WriteLine(string.Format("--------------Finished: {0} !!!--------------------- \n\r", sDirectory));


                            sDirectory = "/camera/frente";
                            Console.WriteLine(string.Format("************Started deleting directory: {0}****************", sDirectory));
                            ftp.DeleteFTPDirectory_new(sDirectory);
                            Console.WriteLine(string.Format("--------------Finished: {0} !!!--------------------- \n\r", sDirectory));


                            sDirectory = "/camera/fondo";
                            Console.WriteLine(string.Format("************Started deleting directory: {0}****************", sDirectory));
                            ftp.DeleteFTPDirectory_new(sDirectory);
                            Console.WriteLine(string.Format("--------------Finished: {0} !!!--------------------- \n\r", sDirectory));

                            sDirectory = "/camera/garage";
                            Console.WriteLine(string.Format("************Started deleting directory: {0}****************", sDirectory));
                            ftp.DeleteFTPDirectory_new(sDirectory);
                            Console.WriteLine(string.Format("--------------Finished: {0} !!!--------------------- \n\r", sDirectory));
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message + ex.StackTrace);
                        }
                    }

                    //private static void OnTimedEvent(object source, ElapsedEventArgs e)
                    //{
                    //    Console.WriteLine("Starting....");
                    //    DeleteFtpFiles();
                    //}
                }
            }
© www.soinside.com 2019 - 2024. All rights reserved.