1. 程式人生 > >c#如何在FTP伺服器上下載資料夾及子資料夾中的檔案

c#如何在FTP伺服器上下載資料夾及子資料夾中的檔案

c#從FTP伺服器上下載資料夾及子資料夾中的檔案需要三個步驟。

1.單個檔案的下載

/*adss表示存放到本地的路徑名,ftpadss表示從FTP伺服器下載的路徑名*/

public void downLoad(string adss, string ftpadss)
        {
            //FileMode常數確定如何開啟或建立檔案,指定作業系統應建立新檔案。
            //FileMode.Create如果檔案已存在,它將被改寫。
            FileStream outputStream = new FileStream(adss, FileMode.Create);
            FtpWebRequest downRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpadss));
            //設定要傳送到FTP伺服器的命令
            downRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            downRequest.KeepAlive = true;
            FtpWebResponse response = (FtpWebResponse)downRequest.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            long c1 = response.ContentLength;
            int bufferSize = 65536;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            outputStream.Close();
            response.Close();
        }

2.遍歷單個資料夾下的所有檔案的名稱,存到一個數組中。

 public string[] getFtpList(string ftpads, string name, string type)
        {
            WebResponse webresp = null;
            StreamReader ftpFileListReader = null;
            FtpWebRequest ftpRequest = null;
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpads + name));
                ftpRequest.Method = type;
                webresp = ftpRequest.GetResponse();
                ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.UTF8);
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            StringBuilder str = new StringBuilder();
            string line = ftpFileListReader.ReadLine();
            while (line != null)
            {
                str.Append(line);
                str.Append("\n");
                line = ftpFileListReader.ReadLine();
            }
            ftpFileListReader.Close();
            webresp.Close();
            string[] ftpFileList = str.ToString().Split('\n');
            return ftpFileList;
        }

3.遞迴資料夾,獲取資料夾及子資料夾中的檔案

public void downFtp(string ftpads, string name, string Myads)
        {
            string downloadDir = Myads + name;
            string ftpdir = ftpads + name;
            string[] fullname = getFtpList(ftpads, name, WebRequestMethods.Ftp.ListDirectoryDetails);
                         
            string[] onlyname = getFtpList(ftpads, name, WebRequestMethods.Ftp.ListDirectory);
         
            if (!Directory.Exists(downloadDir))
            {
                Directory.CreateDirectory(downloadDir);
            }
            foreach (string names in fullname)
            {
                //判斷是否具有資料夾標識<DIR>  
                if (names.Contains("<DIR>"))
                {
                    string olname = names.Split(new string[] { "<DIR>" },
                    StringSplitOptions.None)[1].Trim();
                    downFtp(ftpdir, "//" + olname, downloadDir);
                }
                else
                {
                    foreach (string onlynames in onlyname)
                    {
                        if (onlynames == "" || onlynames == " " || names == "")
                        {
                            break;
                        }
                        else
                        {
                            if (names.Contains(" " + onlynames))
                            {
                                downLoad(downloadDir + "/" + onlynames, ftpads + name + "/" +
                                onlynames);

                            }
                        }
                    }
                }
            }
        }

以上三個方法是最核心的三個方法,登陸FTP伺服器需要使用者名稱和密碼,因此可以在App.config中進行設定。

下面是我自己用於配置的檔案的路徑,大家可以做一個參照。

<configuration>
  <appSettings>
    <add key="FtpServerMain" value="ftp://192.168.232.1:2121/主站模板"/>
    <add key="FtpServerRelay" value="ftp://192.168.232.1:2121/中繼站模板"/>
    <add key="FtpServerMainTemp" value="ftp://192.168.232.1:2121/主站臨站模板"/>
    <add key="FtpServerRelayTemp" value="ftp://192.168.232.1:2121/中繼站臨站模板"/>
    <add key="FtpDefaultUrlTest" value="ftp://192.168.232.1:2121/測試相關/測試配置檔案"/>
    <add key="FtpDefaultUrlRelease" value="ftp://192.168.232.1:2121/釋出資料"/>
    <add key="LoginID" value="ftp"/>
    <add key="LoginPWD" value="123"/>
    <add key="DownloadPath" value="D://"/>
  </appSettings>
</configuration>

以上是從FTP伺服器上下載資料夾及子資料夾中所有的檔案,這個是我自己親身實踐通過的。如果大家有任何問題,請隨時在底下評論。