A Simple FTP Client Using FluentFTP with Json Configuration in C#

Overview

Using the FluentFTP library, we'll build a basic FTP client application in C#. With FluentFTP, you can easily interact with FTP servers programmatically. A JSON file will also be used to store FTP connection details securely as part of configuration management.

File transfer protocols such as FTP (File Transfer Protocol) remain essential for transferring files over networks. This tutorial aims to demonstrate how to create a console application that can upload and download files from an FTP server using FluentFTP, a popular .NET library. For secure storage of FTP connection credentials, we'll use a JSON configuration file.

Prerequisites

Before we begin, ensure you have the following:

  • Visual Studio (or any C# IDE)
  • Basic knowledge of C# programming

Setting Up the Project


Create a Console Application

Start by creating a new C# console application in Visual Studio. Let's call it FluentFTPExample.

Install FluentFTP Package

The FluentFTP package can be installed via NuGet Package Manager or by adding it to your *.csproj file:

<PackageReference Include="FluentFTP" Version="50.0.1" />

Ensure you have the correct version or the latest stable version of FluentFTP.

Prepare Configuration

To store FTP connection details, prepare a JSON configuration file (config.json) in your project directory:

{
  "FtpInfo": {
    "HostName": "hostname.com",
    "Username": "myUsername",
    "Password": "myPassword"
  }
}

Please ensure that your FTP server hostname, username, and password are replaced with hostname.com, myUsername, and myPassword.

Implementing the FTP Client

Now, let's dive into the code to implement our FTP client using FluentFTP. We will create a console app which will have a folder named Models, where we will be extracting the Json data from the JSON file name config.json. 

Step 1

The Models folder creates two public classes named AppSettings and FtpInfo, and within these classes, we will define our properties, which will be used to read from the config.json file.

The file name: FtpInfo.cs please have the following properties as shown in code example below.

namespace FluentFTPExample.Models;
public class FtpInfo
{
    public string HostName { get; set; } = string.Empty;
    public string Username { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
    public string RemoteFilePath { get; set; }=string.Empty;
    public string LocalFilePath { get; set; } = string. Empty;

}

Now in the AppSettings.cs class file please add the following property name FtpInfo has show in the code example below.

namespace FluentFTPExample.Models;
public class AppSettings
{
    public FtpInfo? FtpInfo { get; set; }

}

The next step now is to write the code in the Console App to FTP the file and also to download the file.

Step Two

The console app file name Program.cs as the following code below.

using FluentFTP;
using FluentFTPExample.Models;
using System.Net;
using System.Text.Json;

Console.WriteLine("Hello, from Ziggy Rafiq!");

string ftpHost = string.Empty;
string ftpUser = string.Empty;
string ftpPass = string.Empty;
string ftpRemoteFilePath = string.Empty;
string ftpLocalFilePath = string.Empty;


 
string jsonFilePath = @"..\..\..\config.json";
string jsonString = File.ReadAllText(jsonFilePath);

AppSettings appSettings = JsonSerializer.Deserialize<AppSettings>(jsonString);

if (appSettings?.FtpInfo != null)
{
    ftpHost = appSettings.FtpInfo.HostName;
    ftpUser = appSettings.FtpInfo.Username;
    ftpPass = appSettings.FtpInfo.Password;
    ftpRemoteFilePath = appSettings.FtpInfo.RemoteFilePath;
    ftpLocalFilePath = appSettings.FtpInfo.LocalFilePath;

}
else
{
    Console.WriteLine("Failed to deserialize FTP settings from config.json.");
    return;
}

using (FtpClient client = new FtpClient(ftpHost))
{
    try
    {
        client.Credentials = new NetworkCredential(ftpUser, ftpPass);

        client.Connect();       

        FtpStatus uploadStatus = client.UploadFile(ftpLocalFilePath, ftpRemoteFilePath);
        if (uploadStatus == FtpStatus.Success)
        {
            Console.WriteLine("File uploaded successfully.");
        }
        else
        {
            Console.WriteLine("File upload failed.");
        }
                
        FtpStatus downloadStatus = client.DownloadFile(ftpLocalFilePath, ftpRemoteFilePath);
        if (downloadStatus == FtpStatus.Success)
        {
            Console.WriteLine("File downloaded successfully.");
        }
        else
        {
            Console.WriteLine("File download failed.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
    finally
    {
        client.Disconnect();
    }
}

Console.ReadLine();

Explanation of the Code

  • Reading Configuration: The AppSettings and FtpInfo classes are used to deserialize the JSON structure into strongly-typed C# objects. We read the FTP connection details (HostName, Username, Password) from config.json via System.Text.Json.
  • Using FluentFTP: In FluentFTP, we create an instance of FtpClient and set the credentials with NetworkCredential based on the ftpUser and ftpPass values. Finally, we connect to the server using the client.Connect().
  • Uploading and Downloading Files: Files can be uploaded and downloaded by uploading to remoteUploadFilePath and downloading to downloadPath.
  • Exception Handling: A proper exception-handling system is implemented to catch and display any errors that may occur during FTP operations.

Summary

 In this article, we covered how to create a simple FTP client in C# using FluentFTP. We integrated configuration management by reading FTP connection details from a JSON file, ensuring security and flexibility. As part of this example, FluentFTP is shown in a console application environment, showing how to upload and download files from an FTP server. It is possible to extend this example further to suit more advanced FTP scenarios or to add additional features as needed.  

You will be able to find the source code for this article on my GitHub repository  https://github.com/ziggyrafiq/FluentFtpSolution also, if you have liked this article, please click the like button and also to follow me on LinkedIn https://www.linkedin.com/in/ziggyrafiq/


Recommended Free Ebook
Similar Articles
Capgemini
Capgemini is a global leader in consulting, technology services, and digital transformation.