How to download a file from a URL using C#

Asked

Viewed 5,094 times

3

Developing a C# project I came across the following situation, I need to download files from some URL’s, what is the best way to do this? Would have some way to together the download implement a progress bar?

3 answers

3


You can use the DownloadFileTaskAsync() and then check the status of the task if necessary with Task.

using var client = new WebClient());
var tarefa await client.DownloadFileTaskAsync("http://endereco.aqui/arquivo.txt", "arquivo.txt");

Or it can do synchronously if locking the application while downloading the file with DownloadFile():

using var client = new WebClient());
client.DownloadFile("http://endereco.aqui/arquivo.txt", "arquivo.txt");

Of course you will have to take exception treatment and have other care, but the question is generic.

I put in the Github for future reference.

There are other techniques older but no longer recommended.

0

using (var client = new WebClient())
{
    client.DownloadFile("http://meurepositorio.com/file/imagens/a.jpg", "a.mpeg");
    client.DownloadProgressChanged += WebClientDownloadProgressChanged;
    client.DownloadFileCompleted += WebClientDownloadCompleted;
    Console.WriteLine(@"Baixando o arquivo:");
}

0

creates a form, inserts a text box to type in the url(txtUrl), a button to start the download(button1), a label to show how much was downloaded (label) and a progressibar(progressBar1) to see the progress and inserts the code below:

private void button1_Click(object sender, EventArgs e)
{
    startDownload(txtUrl.Text);
}

private void startDownload(string url)
{
    Thread thread = new Thread(() =>
    {
        WebClient client = new WebClient();
        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
        client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
        String nomeArquivo = Path.GetFileName(url);
        client.DownloadFileAsync(new Uri(url), @"C:\Temp\" + nomeArquivo);
    });
    thread.Start();
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    this.BeginInvoke((MethodInvoker)delegate
    {
        double bytesIn = double.Parse(e.BytesReceived.ToString());
        double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
        double percentage = bytesIn / totalBytes * 100;
        label.Text = "Baixado: " + e.BytesReceived + " of " + e.TotalBytesToReceive;
        progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
    });
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    this.BeginInvoke((MethodInvoker)delegate
    {
        label.Text = "Download Completo";
    });
}

then just customize for your need ps: the code is downloading the file to the folder c: Temp\

Browser other questions tagged

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