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

时间:2012-02-06 19:24:16

标签: 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;
                    }
                }
            }
        }

3 个答案:

答案 0 :(得分:2)

首先,您必须使用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: -

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

}

答案 1 :(得分:1)

示例中使用的ListDirectoryDe​​tails命令只返回一个字符串。您必须手动解析它以构建文件和子目录列表。

答案 2 :(得分:1)

找到http://social.msdn.microsoft.com/Forums/en/ncl/thread/079fb811-3c55-4959-85c4-677e4b20bea3

    string[] files = GetFileList();
    foreach (string file in files)
    {
        Download(file);
    }

    public string[] GetFileList()
    {
        string[] downloadFiles;
        StringBuilder result = new StringBuilder();
        WebResponse response = null;
        StreamReader reader = null;
        try
        {
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
            reqFTP.Proxy = null;
            reqFTP.KeepAlive = false;
            reqFTP.UsePassive = false;
            response = reqFTP.GetResponse();
            reader = new StreamReader(response.GetResponseStream());
            string line = reader.ReadLine();
            while (line != null)
            {
                result.Append(line);
                result.Append("\n");
                line = reader.ReadLine();
            }
            // to remove the trailing '\n'
            result.Remove(result.ToString().LastIndexOf('\n'), 1);
            return result.ToString().Split('\n');
        }
        catch (Exception ex)
        {
            if (reader != null)
            {
                reader.Close();
            }
            if (response != null)
            {
                response.Close();
            }                
            downloadFiles = null;
            return downloadFiles;
        }
    }

    private void Download(string file)
    {                       
        try
        {                
            string uri = "ftp://" + ftpServerIP + "/" + remoteDir + "/" + file;
            Uri serverUri = new Uri(uri);
            if (serverUri.Scheme != Uri.UriSchemeFtp)
            {
                return;
            }       
            FtpWebRequest reqFTP;                
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + remoteDir + "/" + file));                                
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);                
            reqFTP.KeepAlive = false;                
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;                                
            reqFTP.UseBinary = true;
            reqFTP.Proxy = null;                 
            reqFTP.UsePassive = false;
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream responseStream = response.GetResponseStream();
            FileStream writeStream = new FileStream(localDestnDir + "\" + file, FileMode.Create);                
            int Length = 2048;
            Byte[] buffer = new Byte[Length];
            int bytesRead = responseStream.Read(buffer, 0, Length);               
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = responseStream.Read(buffer, 0, Length);
            }                
            writeStream.Close();
            response.Close(); 
        }
        catch (WebException wEx)
        {
            MessageBox.Show(wEx.Message, "Download Error");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Download Error");
        }
    }