c# - 如何提取给定 FTP 地址上所有文件的文件位置(路径和文件名)?

标签 c# .net ftp filesystems

您好,感谢您的关注!

背景

我需要提取给定 FTP 地址上所有文件的文件位置(路径和文件名)。

对于映射网络或本地驱动器上的文件,此代码有效:

foreach(string fileName f in Directory.GetFiles("C\\:SomeDirectory"), "*.*",
                                     SearchOption.AllDirectories)
{
    //do stuff with each file found
}

但这不适用于 FTP 连接。我已经找到了 this MS documentation其中涵盖了 FTPWebRequest 的建立,但它没有告诉我如何遍历找到的每个文件(以及在所有嵌套目录中)。

我在表单应用程序中使用 C#。

问题

如何实现:

foreach(string fileName f in Directory.GetFiles("C\\:SomeDirectory"), "*.*",
                                         SearchOption.AllDirectories)
    {
        //do stuff with each file found
    }

使用 FTP 连接?

非常感谢!!

更新/最终答案

特别感谢@sunk 让这一切顺利进行。我对他的代码做了一个小调整,使其完全递归,以便它可以深入嵌套文件夹。这是最终代码:

       //A list that holds all file locations in all folders of a given FTP address:
        List<string> fnl= new List<string>(); 

        //A string to hold the base FTP address:
        string ftpBase = "ftp://[SOME FTP ADDRESS]";

        //A button-click event.  Can be a stand alone method as well
        private void GetFileLocations(object sender, EventArgs e)
        {
            //Get the file names from the FTP location:
            DownloadFileNames(ftpBase);

            //Once 'DownloadFileNames' has run, we have populated 'fnl'
            foreach(var f in fnl)
            {
                //do stuff
            }        
        }

        //Gets all files in a given FTP address.  RECURSIVE METHOD:
        public void DownloadFileNames(string ftpAddress)
        {
            string uri = ftpAddress;
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
            reqFTP.Credentials = new NetworkCredential("pella", "PellaWA01!");
            reqFTP.EnableSsl = false;
            reqFTP.KeepAlive = false;
            reqFTP.UseBinary = true;
            reqFTP.UsePassive = true;
            reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream responseStream = response.GetResponseStream();
            List<string> files = new List<string>();
            StreamReader reader = new StreamReader(responseStream);
            while (!reader.EndOfStream)
                files.Add(reader.ReadLine());
            reader.Close();
            responseStream.Dispose();

            //Loop through the resulting file names.
            foreach (var fileName in files)
            {
                var parentDirectory = "";

                //If the filename has an extension, then it actually is 
                //a file and should be added to 'fnl'.            
                if (fileName.IndexOf(".") > 0)
                {
                    fnl.Add(ftpAddress.Replace("ftp://pella.upload.akamai.com/140607/pella/",              "http://media.pella.com/") + fileName);
                }
                else
                {
                //If the filename has no extension, then it is just a folder. 
                //Run this method again as a recursion of the original:
                    parentDirectory += fileName + "/";
                    try
                    {
                        DownloadFileNames(ftpAddress + parentDirectory);
                    }
                    catch (Exception)
                    {
                        //throw;
                    }
                }
            }
        }

最佳答案

首先,您必须使用 FTPWebRequest 获取计算机本地的文件名。

WebRequestMethods.Ftp.ListDirectory;

然后使用 foreach {};

这是代码:-

public List<string> DownloadFileNames()
        {
                string uri = "ftp://" + ftpServerIP + "/";
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.EnableSsl = true;
                reqFTP.KeepAlive = false;
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = Settings.UsePassive;
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream responseStream = response.GetResponseStream();
                List<string> files = new List<string>();
                StreamReader reader = new StreamReader(responseStream);
                while (!reader.EndOfStream)
                    files.Add(reader.ReadLine());
                reader.Close();
                responseStream.Dispose();
                return files;
        }

现在你有了列表:-

List<string> FileNameList = DownloadFileNames();
foreach (var fileName in FileNameList)
{

}

关于c# - 如何提取给定 FTP 地址上所有文件的文件位置(路径和文件名)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9165946/

相关文章:

c# - 找不到重载方法

c# - 在相等性测试中使用字符串文字是否会创建新字符串?

c# - 方法属性 TestMethod 和 TestMethod() 之间有什么区别?

c# - 如何使用 C# 在 GridView 中启用或禁用文本框

c# - 单元测试 WCF 错误

c# - 使用 BulkAll 方法嵌套 5.5 重复项

c# - 您将如何正确地异步返回对象集合?

C# 不信任已安装的证书

C# 文件访问错误

php - 在共享主机中仅使用 FTP 部署 Laravel 5