【FTP】C# System.Net.FtpClient庫鏈接ftp服務器(上傳文件)

若是本身單槍匹馬寫一個鏈接ftp服務器代碼那是至關恐怖的(socket通訊),有一個評價較高的dll庫能夠供咱們使用。服務器

那就是System.Net.FtpClient,連接地址:https://netftp.codeplex.comsocket

而後下載該資源,咱們就能夠使用它的函數了。這裏介紹一下如何使用System.Net.FtpClient連接ftp服務器並上傳本身文件至服務器。函數

千萬別忘了添加引用——導入System.Net.FtpClient.dll.spa

還有就是 using System.Net.FtpClient;code

            using System.Net;blog

 1         /// <summary>
 2         /// FTP上傳文件
 3         /// </summary>
 4         /// <param name="strServer">服務器地址</param>
 5         /// <param name="strUser">用戶名</param>
 6         /// <param name="strPassword">密碼</param>
 7         /// <param name="Savepath">服務器用於保存的文件夾路徑,不是服務器根路徑,例如: "/UploadDocumentsSave/"</param>
 8         /// <param name="localpath">本地路徑</param>
 9         /// <param name="filetype">文件類型,例如: ".rte"</param>
10         public void FTPUpload(string strServer, string strUser, string strPassword, string Savepath, string localpath, string filetype)
11         {
12                  FtpClient ftp = new FtpClient();
13                  ftp.Host = strServer;
14                  ftp.Credentials = new NetworkCredential(strUser, strPassword);
15                  ftp.Connect();
16 
17                  string[] files = Directory.GetFiles(localpath, "*" + filetype);
18                  if(files.Length!=0)
19                  {
20                      foreach (string file in files)
21                      {
22                         using (var fileStream = File.OpenRead(file))
23                         using (var ftpStream = ftp.OpenWrite(Savepath+Path.GetFileName(file)))
24                         {
25                             var buffer = new byte[8 * 1024];
26                             int count;
27                             while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
28                             {
29                                 ftpStream.Write(buffer, 0, count);
30                             }
31                         }
32                     }
33                       MessageBox.Show("OK");
34                 }            
35         }

若是FTP服務器內沒有用於保存的文件夾存在,只有一個根文件夾,那麼,第23行就改爲:資源

 using (var ftpStream = ftp.OpenWrite("/"+Path.GetFileName(file)));
相關文章
相關標籤/搜索