C#.NET FTP Manipulation Package – FluentFTP

What happened

Recently in my project, I encountered a client requirement to store files on an FTP server instead of locally on the machine or in a database. Therefore, I started looking into how to easily manipulate FTP in C#.

In the past, my understanding of FTP was limited to using FileZilla manually, and I hadn’t explored programmatic operations with it.

Introduction to FluentFTP

According to the author’s Github introduction, FluentFTP is a tool developed for FTP and FTPS based on .NET, supporting several common operations such as file upload/download, SSL/TLS connections, automatic directory listing parsing, file hashing/verification, file permissions/CHMOD, FTP proxy, FXP transfer, UTF-8 support, Async/await support, Powershell support, and more.

Additionally, it is entirely written in C#, eliminating external dependencies. To use it in your project, you can easily download it via NuGet – NuGet Gallery | FluentFTP 48.0.3

Common Functions

Here, I’ll introduce some functions that I have utilized in the project (additional introductions may be provided later).

Before using any of the features, make sure to establish a connection (remember to include using FluentFTP).

Establishing a Connection

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

	ftp.Connect();
	return ftp;
}


Here is a simple way to establish a shared connection. Since there are different operations on FTP in the project, the connection method is extracted and written independently.

Connection details should include:

  • ftpAddress: IP address of the FTP server (aliases seem to work as well).
  • ftpPort: Port number of the FTP server.
  • ftpAcc, ftpPwd: User account and password for FTP connection.

Additionally, since there is a Connect method, there is also a Disconnect. Typically, it is called after usage to terminate the connection.

Creating a Folder

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 : If the specified directory doesn’t exist, it will be created

This can also assist in creating multiple levels. For example, ftp.CreateDirectory(“pdf\\test”) will create a ‘pdf‘ folder at the root, and underneath it, a subfolder named ‘test‘.

Upload (Single File)

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;
}

In this section, the UploadBytes method is utilized to upload a byte array. The provided example involves transmitting a PDF file to the “pdf” folder on the FTP server.

Furthermore, FtpStatus has three possible values: 0 for Failed, 1 for Success, and 2 for Skipped. The “Skipped” status occurs when the file already exists on the FTP server.

Upload an entire directory to an FTP directory

public static void uploadDir(string uploadDir, string desDir) {
	FtpClient ftp = createFtpClient();

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

ftp.UploadDirectory : Uploads the entire local directory to the specified directory on the FTP server.

The method returns a List of FtpResult objects, which contains the status of each file in the upload process.

Download Single File

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

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

	return arr;
}

Download a file using the out parameter, providing the byte[] and specifying the file location.

In this example, it downloads the previously uploaded PDF.

List the current directory

/// <summary>
/// List the contents of the current directory (non-recursive).
/// </summary>
public void ListAll()
{
    FtpClient ftp = CreateFtpClient();

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

    ftp.Disconnect();
}

Conclusion

This article primarily documents the basic usage of the FluentFTP package.

Updates may follow if more advanced aspects are explored. If you encounter any issues or have questions, feel free to leave a comment, and I’ll look into it.

Although using programs to operate FTP might be less common nowadays, personally, I prefer storing data in databases.

💔 The entire article was written and tested independently. Feel free to quote or reference, but please avoid copying the entire content verbatim.

🧡You can support our team by sharing the post or clicking some ads, Thanks a lot

If you have any problem about this post, please feel free to ask~

Some Random notes

Leave a Reply

Your email address will not be published. Required fields are marked *