C#.NET 操作FTP的套件 – FluentFTP

前言

最近專案中,遇到的客戶檔案要求將檔案存在FTP上,而不是本機實體路徑或是資料庫。

故尋找著C#中該如何簡單操作FTP,畢竟以前對FTP的概念只有透過 FileZilla 拉一拉,沒透過程式操作呢~

FluentFTP介紹

根據作者的Github介紹,FluentFTP是基於 .NET開發的 FTP以及FTPS的工具,支援了常見的數個操作 – 文件上傳/下載、SSL/TLS 連接、自動目錄清單解析、文件雜湊/校驗、文件權限/CHMOD、FTP 代理、FXP 傳輸、UTF-8 支援、Async/await 支援、Powershell 支援等功能。

另外,它完全使用C#編寫,故沒有外部的依賴。

想要在專案中使用,可以直接使用 NuGet 下載 – NuGet Gallery | FluentFTP 48.0.3

常見功能

這邊介紹一下,一些我在專案中有操作到的功能 (之後可能再補介紹)

在使用所有功能前,都要先建立連線 (記得先引用 using FluentFTP)

建立連線

private static FtpClient createFtpClient() {
	FtpClient ftp = new FtpClient(ftpAddress, ftpPort);
	ftp.Credentials = new System.Net.NetworkCredential(ftpAcc, ftpPwd);

	ftp.Connect();
	return ftp;
}

這邊是一個簡單的共用連線的方式,因為案子中對FTP有不同的操作,故將連線的方式拉出來獨立寫。

連線須提供

  • ftpAddress : FTP server 的IP地址 (別名好像也行)
  • ftpPort : FTP server 的port號
  • ftpAcc、ftpPwd : FTP連線的使用者帳號以及密碼

另外,既然有 Connect 就有 Disconnect,通常在使用後會呼叫來中斷連線

建立資料夾

public static bool initDict() {
	bool result = false;
	try
	{
		FtpClient ftp = createFtpClient();
		result = ftp.CreateDirectory("pdf");

		ftp.Disconnect();
	}
	catch (Exception ex) {
		throw ex;
	}

	return result;
}

ftp.CreateDirectory 要是指定的資料夾不存在,就會建立

另外,這裡是可以協助建立多層的,例如 ftp.CreateDirectory(“pdf\\test”) 就會在根目錄底下先建立一個pdf 資料夾,另外在其底下在建立一個subfolder test

上傳(單一檔案)

public static bool uploadPdf(HttpPostedFileBase file) {
	bool result = false;
	FtpClient ftp = createFtpClient();
	
	byte[] fileBytes;
	using (BinaryReader reader = new BinaryReader(file.InputStream))
	{
		fileBytes = reader.ReadBytes(file.ContentLength);
	}

	FtpStatus ftpStatus = ftp.UploadBytes(fileBytes, "pdf\\" + file.FileName);

	ftp.Disconnect();
	return result;
}

上傳這邊是用 UploadBytes 來上傳byte array,這個範例就是傳pdf到 FTP server上的pdf folder底下

另外FtpStatus 分為 0 Failed、1 Success、2 Skipped

會出現Skipped的狀況就是該檔案已經存在FTP server的時候

上傳(整個目錄 to FTP目錄)

/// <summary>
/// 上傳整個目錄到指定ftp目錄
/// </summary>
public static void uploadDir(string uploadDir, string desDir) {
	FtpClient ftp = createFtpClient();

	ftp.CreateDirectory(desDir);
	List<FtpResult> res = ftp.UploadDirectory(uploadDir, desDir);
	ftp.Disconnect();
}

將整個本機目錄上傳到FTP指定目錄,會回傳一個List of FtpResult,包含了所有檔案的狀態

下載

public static byte[] downloadPdf(string pdfName) {
	byte[] arr;
	FtpClient ftp = createFtpClient();

	bool res = ftp.DownloadBytes(out arr, "pdf\\" + pdfName);
	ftp.Disconnect();

	return arr;
}

用 out 的方式傳出 byte[],傳入參數為檔案位置

以這個例子來說,就是下載前面上傳的PDF

列出當前目錄

/// <summary>
/// 列出當前的目錄 (不會向下)
/// </summary>
public void listAll() {
	FtpClient ftp = createFtpClient();

	foreach (var item in ftp.GetListing())
	{
		Debug.WriteLine(item.ToString());
	}

	ftp.Disconnect();
}

只會列出當前目錄,不會recursive向下


結論

這一篇主要就是記錄下 FluentFTP 這個套件的一些基本使用

之後要是用到更多層面可能會再更新,如有遇上其他問題,也可以留言給我,我再去研究看看

雖然現在用程式操作FTP應該還是比較少啦,至少我都是perfer存在DB裡的~

希望文章有幫上一點忙,畢竟對專案來說沒有最好的做法,只有最合適的做法

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

套件的github網址 : GitHub – robinrodricks/FluentFTP: An FTP and FTPS client for .NET & .NET Standard, optimized for speed. Provides extensive FTP commands, File uploads/downloads, SSL/TLS connections, Automatic directory listing parsing, File hashing/checksums, File permissions/CHMOD, FTP proxies, FXP support, UTF-8 support, Async/await support, Powershell support and more. Written entirely in C#.

其他筆記們

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *