本文是利用C# 實現FTP客戶端的小例子,主要實現上傳,下載,刪除等功能,以供學習分享使用。
思路:
通過讀取FTP站點的目錄信息,列出對應的文件及文件夾。
雙擊目錄,則顯示子目錄,如果是文件,則點擊右鍵,進行下載和刪除操作。
通過讀取本地電腦的目錄,以樹狀結構展示,選擇本地文件,右鍵進行上傳操作。
涉及知識點:
FtpWebRequest【實現文件傳輸協議 (FTP) 客戶端】 / FtpWebResponse【封裝文件傳輸協議 (FTP) 服務器對請求的響應】Ftp的操作主要集中在兩個類中。
FlowLayoutPanel  【流布局面板】表示一個沿水平或垂直方向動態排放其內容的面板。
ContextMenuStrip 【快捷菜單】 主要用于右鍵菜單。
資源文件:Resources 用于存放圖片及其他資源。
效果圖如下
左邊:雙擊文件夾進入子目錄,點擊工具欄按鈕‘上級目錄'返回。文件點擊右鍵進行操作。
右邊:文件夾則點擊前面+號展開。文件則點擊右鍵進行上傳。

核心代碼如下
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net;using System.Text;using System.Threading;using System.Threading.Tasks;namespace FtpClient{  public class FtpHelper  {    #region 屬性與構造函數    /// <summary>    /// IP地址    /// </summary>    public string IpAddr { get; set; }    /// <summary>    /// 相對路徑    /// </summary>    public string RelatePath { get; set; }    /// <summary>    /// 端口號    /// </summary>    public string Port { get; set; }    /// <summary>    /// 用戶名    /// </summary>    public string UserName { get; set; }    /// <summary>    /// 密碼    /// </summary>    public string Password { get; set; }        public FtpHelper() {    }    public FtpHelper(string ipAddr, string port, string userName, string password) {      this.IpAddr = ipAddr;      this.Port = port;      this.UserName = userName;      this.Password = password;    }    #endregion    #region 方法    /// <summary>    /// 下載文件    /// </summary>    /// <param name="filePath"></param>    /// <param name="isOk"></param>    public void DownLoad(string filePath, out bool isOk) {      string method = WebRequestMethods.Ftp.DownloadFile;      var statusCode = FtpStatusCode.DataAlreadyOpen;      FtpWebResponse response = callFtp(method);      ReadByBytes(filePath, response, statusCode, out isOk);    }    public void UpLoad(string file,out bool isOk)    {      isOk = false;      FileInfo fi = new FileInfo(file);      FileStream fs = fi.OpenRead();      long length = fs.Length;      string uri = string.Format("ftp://{0}:{1}{2}", this.IpAddr, this.Port, this.RelatePath);      FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);      request.Credentials = new NetworkCredential(UserName, Password);      request.Method = WebRequestMethods.Ftp.UploadFile;      request.UseBinary = true;      request.ContentLength = length;      request.Timeout = 10 * 1000;      try      {        Stream stream = request.GetRequestStream();        int BufferLength = 2048; //2K          byte[] b = new byte[BufferLength];        int i;        while ((i = fs.Read(b, 0, BufferLength)) > 0)        {          stream.Write(b, 0, i);        }        stream.Close();        stream.Dispose();        isOk = true;      }      catch (Exception ex)      {        Console.WriteLine(ex.ToString());      }      finally {        if (request != null)        {          request.Abort();          request = null;        }      }    }    /// <summary>    /// 刪除文件    /// </summary>    /// <param name="isOk"></param>    /// <returns></returns>    public string[] DeleteFile(out bool isOk) {      string method = WebRequestMethods.Ftp.DeleteFile;      var statusCode = FtpStatusCode.FileActionOK;      FtpWebResponse response = callFtp(method);      return ReadByLine(response, statusCode, out isOk);    }    /// <summary>    /// 展示目錄    /// </summary>    public string[] ListDirectory(out bool isOk)    {      string method = WebRequestMethods.Ftp.ListDirectoryDetails;      var statusCode = FtpStatusCode.DataAlreadyOpen;      FtpWebResponse response= callFtp(method);      return ReadByLine(response, statusCode, out isOk);    }    /// <summary>    /// 設置上級目錄    /// </summary>    public void SetPrePath()    {      string relatePath = this.RelatePath;      if (string.IsNullOrEmpty(relatePath) || relatePath.LastIndexOf("/") == 0 )      {        relatePath = "";      }      else {        relatePath = relatePath.Substring(0, relatePath.LastIndexOf("/"));      }      this.RelatePath = relatePath;    }    #endregion    #region 私有方法    /// <summary>    /// 調用Ftp,將命令發往Ftp并返回信息    /// </summary>    /// <param name="method">要發往Ftp的命令</param>    /// <returns></returns>    private FtpWebResponse callFtp(string method)    {      string uri = string.Format("ftp://{0}:{1}{2}", this.IpAddr, this.Port, this.RelatePath);      FtpWebRequest request; request = (FtpWebRequest)FtpWebRequest.Create(uri);      request.UseBinary = true;      request.UsePassive = true;      request.Credentials = new NetworkCredential(UserName, Password);      request.KeepAlive = false;      request.Method = method;      FtpWebResponse response = (FtpWebResponse)request.GetResponse();      return response;    }    /// <summary>    /// 按行讀取    /// </summary>    /// <param name="response"></param>    /// <param name="statusCode"></param>    /// <param name="isOk"></param>    /// <returns></returns>    private string[] ReadByLine(FtpWebResponse response, FtpStatusCode statusCode,out bool isOk) {      List<string> lstAccpet = new List<string>();      int i = 0;      while (true)      {        if (response.StatusCode == statusCode)        {          using (StreamReader sr = new StreamReader(response.GetResponseStream()))          {            string line = sr.ReadLine();            while (!string.IsNullOrEmpty(line))            {              lstAccpet.Add(line);              line = sr.ReadLine();            }          }          isOk = true;          break;        }        i++;        if (i > 10)        {          isOk = false;          break;        }        Thread.Sleep(200);      }      response.Close();      return lstAccpet.ToArray();    }    private void ReadByBytes(string filePath,FtpWebResponse response, FtpStatusCode statusCode, out bool isOk)    {      isOk = false;      int i = 0;      while (true)      {        if (response.StatusCode == statusCode)        {          long length = response.ContentLength;          int bufferSize = 2048;          int readCount;          byte[] buffer = new byte[bufferSize];          using (FileStream outputStream = new FileStream(filePath, FileMode.Create))          {            using (Stream ftpStream = response.GetResponseStream())            {              readCount = ftpStream.Read(buffer, 0, bufferSize);              while (readCount > 0)              {                outputStream.Write(buffer, 0, readCount);                readCount = ftpStream.Read(buffer, 0, bufferSize);              }            }          }          break;        }        i++;        if (i > 10)        {          isOk = false;          break;        }        Thread.Sleep(200);      }      response.Close();    }    #endregion  }  /// <summary>  /// Ftp內容類型枚舉  /// </summary>  public enum FtpContentType  {    undefined = 0,    file = 1,    folder = 2  }}源碼鏈接如下:案例
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答