How to implement progressiBar in FTP download

Asked

Viewed 41 times

2

I need to enter the download transfer rate by FTP on progressBar of my Form with the code below:

private void Download(string filePath, string fileName)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerIP + "/" + fileName);
        request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        request.Method = WebRequestMethods.Ftp.DownloadFile;

        using (Stream ftpStream = request.GetResponse().GetResponseStream())
        using (Stream fileStream = File.Create(filePath + "\\" + fileName))
        {
            byte[] buffer = new byte[10240];
            int read;
            while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                fileStream.Write(buffer, 0, read);
            }
        }
    }

What needs to be done?

1 answer

2


In your case you can do as follows:

private int GetFileSize(string url, NetworkCredential nc)
{
    // Query size of the file to be downloaded
    WebRequest sizeRequest = WebRequest.Create(url);

    sizeRequest.Credentials = nc;
    sizeRequest.Method = WebRequestMethods.Ftp.GetFileSize;

    return (int)sizeRequest.GetResponse().ContentLength;
}

private void Download(string filePath, string fileName)
{
    string url = "ftp://" + ftpServerIP + "/" + fileName;
    NetworkCredential nc = new NetworkCredential(ftpUserID, ftpPassword);
    int size = GetFileSize(url, nc);

    progressBar1.Invoke((MethodInvoker)(() => progressBar1.Maximum = size));

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
    request.Credentials = nc;
    request.Method = WebRequestMethods.Ftp.DownloadFile;

    using (Stream ftpStream = request.GetResponse().GetResponseStream())
    using (Stream fileStream = File.Create(filePath + "\\" + fileName))
    {
        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.Invoke((MethodInvoker)(() => progressBar1.Value = position));
        }
    }
}

It should be noted that the Download has to be evoked in a new Thread, otherwise will block the UI and will not be able to see progress:

private void button1_Click(object sender, EventArgs e)
{
    // Run Download on background thread
    Task.Factory.StartNew(() => Download());
}

It is also necessary to have a ProgressBar by name progressBar1.

  • Gave this 'System.Threading.Tasks.Task' does not contain a definition for 'Run'

  • 1

    The project is Winforms?

  • Yes, and NetFramework 4.0

  • 1

    Ha, ok, version 4.0 does not have this method. Edited answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.