簡體   English   中英

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

[英]How do I pull the file locations (path and filename) for all files at a given FTP address?

嗨,謝謝你的期待!

背景

我需要為給定FTP地址的所有文件提取文件位置(路徑和文件名)。

對於映射網絡或本地驅動器上的文件,此代碼將起作用:

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

但這不適用於FTP連接。 我已經找到了這個MS文檔 ,它涵蓋了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)
{

}

示例中使用的ListDirectoryDe​​tails命令只返回一個字符串。 您必須手動解析它以構建文件和子目錄列表。

發現於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");
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM