A Comprehensive Guide to Using FTP with C#: Upload, Download, and More

A Comprehensive Guide to Using FTP with C#: Upload, Download, and More
In this article [Show more]

    A Comprehensive Guide to Using FTP with C#: Upload, Download, and More

    File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one host to another over a TCP-based network. In C#, you can interact with FTP servers using different libraries and classes. This guide will cover several methods to handle FTP operations, including FtpWebRequest, the FluentFTP library, and HttpClient.

    1. Introduction to C# FTP

    FTP is commonly used for transferring files between a client and a server. In C#, you can use built-in classes and external libraries to handle FTP operations. This guide will explore:

    • Using FtpWebRequest for FTP operations
    • Utilizing the FluentFTP library for advanced features
    • Handling FTP uploads and downloads with HttpClient

    2. Using FtpWebRequest in C#

    The FtpWebRequest class is part of the System.Net namespace and provides a way to interact with FTP servers. Below is an example of how to upload and download files using FtpWebRequest.

    FTP Upload Example

    Here's how you can upload a file to an FTP server using FtpWebRequest:

     

    using System;
    using System.IO;
    using System.Net;
    
    class Program
    {
        static void Main()
        {
            string ftpServer = "ftp://example.com/";
            string filePath = "path/to/local/file.txt";
            string ftpUsername = "username";
            string ftpPassword = "password";
    
            UploadFile(ftpServer, filePath, ftpUsername, ftpPassword);
        }
    
        static void UploadFile(string ftpServer, string filePath, string username, string password)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + Path.GetFileName(filePath));
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);
    
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (Stream requestStream = request.GetRequestStream())
            {
                fileStream.CopyTo(requestStream);
            }
    
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                Console.WriteLine($"Upload File Complete, status {response.StatusDescription}");
            }
        }
    }
    

    FTP Download Example

    To download a file from an FTP server, you can use the following code:

     

    FTP Download Example
    To download a file from an FTP server, you can use the following code:

    3. Using FluentFTP Library

    FluentFTP is a popular third-party library that simplifies FTP operations in C#. It provides an easy-to-use API and supports modern FTP features. To use FluentFTP, first, install it via NuGet:

    dotnet add package FluentFTP
    

    FluentFTP Upload Example

    Here’s how to upload a file using FluentFTP:

    using System;
    using FluentFTP;
    using System.Net;
    
    class Program
    {
        static void Main()
        {
            string ftpServer = "ftp://example.com/";
            string filePath = "path/to/local/file.txt";
            string ftpUsername = "username";
            string ftpPassword = "password";
    
            UploadFile(ftpServer, filePath, ftpUsername, ftpPassword);
        }
    
        static void UploadFile(string ftpServer, string filePath, string username, string password)
        {
            FtpClient client = new FtpClient(ftpServer, new NetworkCredential(username, password));
            client.Connect();
    
            client.UploadFile(filePath, Path.GetFileName(filePath));
            
            client.Disconnect();
            Console.WriteLine("Upload Complete");
        }
    }
    

     

    FluentFTP Download Example

    To download a file using FluentFTP, use the following code:

     

    using System;
    using FluentFTP;
    using System.IO;
    using System.Net;
    
    class Program
    {
        static void Main()
        {
            string ftpServer = "ftp://example.com/";
            string remoteFile = "remote/file.txt";
            string localFile = "path/to/local/file.txt";
            string ftpUsername = "username";
            string ftpPassword = "password";
    
            DownloadFile(ftpServer, remoteFile, localFile, ftpUsername, ftpPassword);
        }
    
        static void DownloadFile(string ftpServer, string remoteFile, string localFile, string username, string password)
        {
            FtpClient client = new FtpClient(ftpServer, new NetworkCredential(username, password));
            client.Connect();
    
            using (FileStream fs = new FileStream(localFile, FileMode.Create, FileAccess.Write))
            {
                client.DownloadFile(fs, remoteFile);
            }
    
            client.Disconnect();
            Console.WriteLine("Download Complete");
        }
    }

    4. Using HttpClient for FTP Operations

    While HttpClient is not typically used for FTP operations, you can use it to interact with FTP servers in certain scenarios. However, it’s generally recommended to use FtpWebRequest or FluentFTP for better FTP-specific functionalities.

    HttpClient FTP Download Example

    Here’s an example of using HttpClient to download a file via FTP, though it’s not the most straightforward method:

    using System;
    using System.Net.Http;
    using System.IO;
    using System.Threading.Tasks;
    
    class Program
    {
        static async Task Main()
        {
            string ftpServer = "ftp://example.com/";
            string remoteFile = "remote/file.txt";
            string localFile = "path/to/local/file.txt";
    
            await DownloadFileAsync(ftpServer, remoteFile, localFile);
        }
    
        static async Task DownloadFileAsync(string ftpServer, string remoteFile, string localFile)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(ftpServer + remoteFile);
    
                using (FileStream fs = new FileStream(localFile, FileMode.Create, FileAccess.Write))
                {
                    await response.Content.CopyToAsync(fs);
                }
            }
    
            Console.WriteLine("Download Complete");
        }
    }

     

    Conclusion

    In this guide, we've explored several methods for handling FTP operations in C#, including using FtpWebRequest, the FluentFTP library, and HttpClient. Each method has its use cases, with FtpWebRequest and FluentFTP being more suitable for typical FTP tasks. By following the examples provided, you should be able to perform FTP upload and download operations effectively in your C# applications.

    Feel free to adapt the provided examples to fit your specific requirements and explore further based on your needs.

     

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments