How to download a file from a URL using C #

3

Developing a project in C # I came across the following situation, I need to download files from some URL's, what is the best way to do this? Would there be any way to download a progress bar together?

    
asked by anonymous 17.03.2017 / 18:55

3 answers

3

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

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

Or you can synchronize if you crash 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 do exception handling and have other care, but the question is generic.

I've placed it on GitHub for future reference .

There are other older techniques but are no longer recommended.

    
17.03.2017 / 19:18
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:");
}
    
17.03.2017 / 19:17
0

creates a form, inserts a text box to type the url (txtUrl), a button to start the download (button1), a label to show how much has been downloaded (label) and a progressbar (progressBar1) to see the progress and insert 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 c: \ Temp \

    
17.03.2017 / 19:19