How to Download files with FTP in C#

By FoxLearn 11/15/2024 9:31:00 AM   10.56K
You can download files from an FTP server in a C# Windows Forms Application using the WebRequest class.

How to download files from ftp server in C#

Open your Visual Studio, then create a new Windows Forms application project.

Next, Drag and drop the TextBox, Label, Progress Bar and Button controls from the Visual Studio toolbox to your winform, then you can layout your winform as shown below.

download file using ftp in c#

Create a FileDownload method allows you to download the file from FTP server in c# code as shown below.

// c# ftp
private void FileDownload()
{
    try
    {
        NetworkCredential credentials = new NetworkCredential(txtUserName.Text, txtPassword.Text);
        lblStatus.BeginInvoke(new Action(() =>
        {
            lblStatus.Text = "Downloading...";
        }));
        WebRequest sizeRequest = WebRequest.Create(txtUrl.Text);
        sizeRequest.Credentials = credentials;
        sizeRequest.Method = WebRequestMethods.Ftp.GetFileSize;
        int size = (int)sizeRequest.GetResponse().ContentLength;
        progressBar1.Invoke((MethodInvoker)(() => progressBar1.Maximum = size));
        WebRequest request = WebRequest.Create(txtUrl.Text);
        request.Credentials = credentials;
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        using (Stream ftpStream = request.GetResponse().GetResponseStream())
        {
            using (Stream fileStream = File.Create($"{Application.StartupPath}\\{txtFileName.Text}"))
            {
                byte[] buffer = new byte[10240];
                int read;
                while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fileStream.Write(buffer, 0, read);
                    int position = (int)fileStream.Position;
                    progressBar1.BeginInvoke(new Action(() =>
                    {
                        progressBar1.Value = position;
                    }));
                    if (position == size)
                    {
                        lblStatus.BeginInvoke(new Action(() =>
                        {
                            lblStatus.Text = "Finished";
                        }));
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

First, We retrieves FTP credentials (username and password) from text fields txtUserName.Text and txtPassword.Text.

A request is made to the FTP server to get the file's size using the GetFileSize method. This information is then used to set the maximum value for a progress bar (progressBar1).

A second request is created to download the file from the FTP server using the DownloadFile method. The request is authenticated with the credentials provided earlier.

The file is downloaded in chunks (buffered in 10 KB increments) from the FTP server's response stream (ftpStream). Each chunk is written to a local file on the system (using File.Create), and progress is updated by modifying the value of progressBar1.

As the file is being downloaded, the progress bar is updated to show the download's progress. Once the file is completely downloaded, the status label (lblStatus) is updated to show "Finished."

Finally, Add code to handle the Download button click event allows you to using c# ftp server as shown below.

private void btnDownload_Click(object sender, EventArgs e)
{
    Task.Run(() => FileDownload());
}

Press F5 to run your project, then enter the url, username, password, filename and click the download button to download the files from your ftp server using visual c#.

To play the demo you should create a ftp server. This approach provides a simple, user-friendly way to download files from an FTP server while displaying progress to the user.

Related