Windows Forms: Download files with FTP in C#

This post shows you how to download files from ftp server in C#.NET Windows Forms Application.

Drag 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 the FileDownload method allows you to download the file from FTP server in c# code as shown below.

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

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# tutorial. To play the demo you should create a ftp server.