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

.NET 2.0 內建 FTP 功能完整實作指南(C#)

     編輯:關於C#

.NET Framework 2.0 原生支援 FTP 協定,透過 FtpWebRequest / FtpWebResponse 即可實作上傳、下載、列表、刪除、重命名等操作,無需第三方套件。本文提供完整可用的 C# 範例代碼。

核心步驟

  1. 建立 FtpWebRequest 指向 FTP 伺服器 URI
  2. 設定 Method 屬性(WebRequestMethods.Ftp.UploadFile、DownloadFile、ListDirectory 等)
  3. 配置屬性:Credentials(帳密)、UseBinary(二進位/ASCII)、UsePassive(被動模式)、KeepAlive、EnableSsl
  4. 取得請求串流(上傳)或回應串流(下載/列表)
  5. 讀寫串流,完成後關閉串流與回應物件

關鍵屬性說明

  • UseBinary:二進位模式適用所有檔案;ASCII 模式僅限純文字檔。建議預設使用二進位。
  • UsePassive:被動模式由客戶端發起資料連線,穿透防火牆能力優於主動模式,建議預設開啟。
  • EnableSsl:若伺服器支援 FTPS,務必設為 true,否則帳密明文傳輸極不安全。
  • ContentLength:上傳時設定可讓伺服器預知檔案大小,但客戶端端不強制要求。

上傳檔案範例

private void Upload(string filename)
{
    FileInfo fileInf = new FileInfo(filename);
    string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
    reqFTP.KeepAlive = false;
    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
    reqFTP.UseBinary = true;
    reqFTP.ContentLength = fileInf.Length;

    const int buffLength = 2048;
    byte[] buff = new byte[buffLength];
    int contentLen;

    using (FileStream fs = fileInf.OpenRead())
    using (Stream strm = reqFTP.GetRequestStream())
    {
        while ((contentLen = fs.Read(buff, 0, buffLength)) != 0)
        {
            strm.Write(buff, 0, contentLen);
        }
    }
}

下載檔案範例

private void Download(string filePath, string fileName)
{
    string fullPath = Path.Combine(filePath, fileName);
    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
    reqFTP.UseBinary = true;
    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

    using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse())
    using (Stream ftpStream = response.GetResponseStream())
    using (FileStream outputStream = new FileStream(fullPath, FileMode.Create))
    {
        byte[] buffer = new byte[2048];
        int readCount;
        while ((readCount = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            outputStream.Write(buffer, 0, readCount);
        }
    }
}

取得檔案清單

public string[] GetFileList()
{
    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
    reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
    reqFTP.UseBinary = true;
    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

    using (WebResponse response = reqFTP.GetResponse())
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        string result = reader.ReadToEnd().TrimEnd('\n');
        return result.Split('\n');
    }
}

其他操作

  • 刪除:Method = WebRequestMethods.Ftp.DeleteFile
  • 重命名:設定 RenameTo 屬性,Method = WebRequestMethods.Ftp.Rename
  • 建立目錄:Method = WebRequestMethods.Ftp.MakeDirectory
  • 取得檔案大小:Method = WebRequestMethods.Ftp.GetFileSize,回應的 ContentLength 即為大小

安全性提醒

  • 生產環境務必啟用 EnableSsl = true,否則帳密明文傳輸。
  • 捕獲 WebException 檢查 Response 的 StatusCode 與 StatusDescription 進行錯誤診斷。
  • 權限不足會拋出 SecurityException。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved