How to Upload files with FTP in C#

By FoxLearn 11/27/2024 8:25:16 AM   15.44K
Uploading a file to an FTP server in a C# Windows Forms application involves using the System.Net namespace, particularly the FtpWebRequest class.

Uploading files to an FTP server is a common requirement for applications that manage file storage or share files across systems. In this article, we will walk through how to build a simple FTP file uploader using C# Windows Forms.

The example leverages the FtpWebRequest class for FTP communication and a BackgroundWorker to manage file uploads while updating the user interface with progress.

How to Upload files with FTP in C#?

Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "FTPUpload" and then click OK

Drag and drop Label, TextBox, Button, ProgressBar controls from the Visual Toolbox onto your form designer, then design your form as shown below.

ftp upload c#

Building an FTP File Uploader in C# Windows Forms

You can create an FtpSetting struct to encapsulate all the necessary details for an FTP upload:

// Define a struct to store FTP login details and file information
struct FtpSetting
{
    public string Server { get; set; } // FTP server URL.
    public string Username { get; set; } // Authentication credentials.
    public string Password { get; set; } // Authentication credentials.
    public string FileName { get; set; } // Name of the file to upload.
    public string FullName { get; set; } // Full local path of the file.
}

 

Handles the actual file upload in a background thread.

Uses FtpWebRequest to connect to the FTP server and stream the file in chunks of 1024 bytes.

// BackgroundWorker handles the file upload
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // Get the file path and FTP server details
    string fileName = ((FtpSetting)e.Argument).FileName;
    string fullName = ((FtpSetting)e.Argument).FullName;
    string userName = ((FtpSetting)e.Argument).Username;
    string password = ((FtpSetting)e.Argument).Password;
    string server = ((FtpSetting)e.Argument).Server;
    // Create an FTP request
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", server, fileName)));
    request.Method = WebRequestMethods.Ftp.UploadFile;
    // Provide credentials
    request.Credentials = new NetworkCredential(userName, password);
    Stream ftpStream = request.GetRequestStream();
    FileStream fs = File.OpenRead(fullName);
    byte[] buffer = new byte[1024];
    double total = (double)fs.Length;
    int byteRead = 0;
    double read = 0;
    do
    {
        if (!backgroundWorker.CancellationPending)
        {
            //Upload file & update process bar
            byteRead = fs.Read(buffer, 0, 1024);
            ftpStream.Write(buffer, 0, byteRead);
            read += (double)byteRead;
            double percentage = read / total * 100;
            backgroundWorker.ReportProgress((int)percentage);
        }
    }
    while (byteRead != 0);
    fs.Close();
    ftpStream.Close();
}

Reports upload progress to the UI thread.

Updates the ProgressBar and the status label with the current upload percentage.

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    lblStatus.Text = $"Uploaded {e.ProgressPercentage} %";
    progressBar.Value = e.ProgressPercentage;
    progressBar.Update();
}

Notifies the user when the upload is complete.

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    lblStatus.Text = "Upload complete !";
}

Use the OpenFileDialog to select the file to upload. The selected file's details are passed to the BackgroundWorker via the FtpSetting struct.

private void btnUpload_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Multiselect = false, ValidateNames = true, Filter = "All files|*.*" })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            FileInfo fi = new FileInfo(ofd.FileName);
            _inputParameter.Username = txtUserName.Text;
            _inputParameter.Password = txtPassword.Text;
            _inputParameter.Server = txtServer.Text;
            _inputParameter.FileName = fi.Name;
            _inputParameter.FullName = fi.FullName;
            backgroundWorker.RunWorkerAsync(_inputParameter);
        }
    }
}

Below is the code that handles the FTP upload form.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FTPUpload
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        FtpSetting _inputParameter; 
    }
}

This example demonstrates how to build an FTP file uploader using a BackgroundWorker. By structuring the FTP details in a struct and separating the upload logic into events, the code is clean, modular, and maintainable.

VIDEO TUTORIAL