首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 實作 FTP 客戶端:上傳、下載、目錄操作完整類別

     編輯:關於C語言

自訂 FTPClient 類別完整實作

本文提供一個功能完整的 FTPClient 類別,封裝連線、登入、檔案上傳下載、目錄管理、重命名、刪除等操作,採用 Socket 直接實作 FTP 協定(主動/被動模式),適合深入理解 FTP 流程或無法使用 FtpWebRequest 的環境。

主要功能

  • 連線/斷線管理,支援多型建構子
  • 二進位/ASCII 傳輸模式切換
  • 檔案上傳 (Put)、下載 (Get)、批次操作
  • 目錄建立 (MkDir)、刪除 (RmDir)、切換 (ChDir)
  • 檔案刪除、重命名、取得大小、列表
  • 被動模式 (PASV) 資料連線建立

使用範例

FTPClient ftp = new FTPClient();
ftp.RemoteHost = "ftp.example.com";
ftp.RemoteUser = "user";
ftp.RemotePass = "pass";
ftp.RemotePath = "/public";
ftp.RemotePort = 21;

try
{
    ftp.Connect();
    // 下載單一檔案
    ftp.Get("remote.txt", @"C:\Local\", "local.txt");
    // 上傳檔案
    ftp.Put(@"C:\Local\upload.txt");
    ftp.DisConnect();
}
catch (Exception ex)
{
    MessageBox.Show($"FTP 錯誤: {ex.Message}");
}

核心方法節錄

// 建立被動模式資料 Socket
private Socket CreateDataSocket()
{
    SendCommand("PASV");
    if (iReplyCode != 227) throw new IOException(strReply.Substring(4));

    // 解析回應中的 IP 與 Port
    int idx1 = strReply.IndexOf('(');
    int idx2 = strReply.IndexOf(')');
    string[] parts = strReply.Substring(idx1 + 1, idx2 - idx1 - 1).Split(',');
    string ip = $"{parts[0]}.{parts[1]}.{parts[2]}.{parts[3]}";
    int port = (int.Parse(parts[4]) << 8) + int.Parse(parts[5]);

    Socket dataSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    dataSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
    return dataSocket;
}

// 下載檔案核心邏輯
public void Get(string remoteFile, string localFolder, string localFileName)
{
    SetTransferType(TransferType.Binary);
    using (FileStream fs = new FileStream(Path.Combine(localFolder, localFileName), FileMode.Create))
    using (Socket dataSocket = CreateDataSocket())
    {
        SendCommand($"RETR {remoteFile}");
        // 檢查回應碼 150/125/226/250
        byte[] buffer = new byte[512];
        int bytesRead;
        while ((bytesRead = dataSocket.Receive(buffer)) > 0)
            fs.Write(buffer, 0, bytesRead);
    }
}

設計亮點

  • 封裝底層 Socket 與 FTP 指令交換細節。
  • 統一的回應碼檢查與例外拋出機制。
  • 支援大檔案串流傳輸,避免記憶體壓力。

現代替代方案: .NET 內建 FtpWebRequest 或第三方函式庫 FluentFTP 提供更高層抽象。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved