How to Download files with FTP in C#

By FoxLearn 7/19/2024 2:16:19 AM   10.27K
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.

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.

Related