Como baixar um arquivo de uma URL em c #?


352

O que é uma maneira simples de baixar um arquivo de um caminho de URL?


13
Dê uma olhada no System.Net.WebClient
seanb

Respostas:


475
using (var client = new WebClient())
{
    client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}

24
A melhor solução de todos os tempos, mas gostaria de adicionar uma linha importante 'client.Credentials = new NetworkCredential ("UserName", "Password");'
Desenvolvedor

3
Um efeito colateral bem-vindo: Este método também suporta arquivos locais como 1º parâmetro
oo_dev

O doc MSDN fez menção de usar HttpClient agora, em vez: docs.microsoft.com/en-us/dotnet/api/...
StormsEngineering

Embora eu ache que o WebClient parece uma solução muito mais direta e simples.
StormsEngineering

11
@ copa017: Ou perigoso, se, por exemplo, o URL for fornecido pelo usuário e o código C # for executado em um servidor web.
Heinzi 25/04

177

Incluir este espaço para nome

using System.Net;

Faça o download de forma assíncrona e coloque uma ProgressBar para mostrar o status do download no próprio thread da interface do usuário

private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadProgressChanged += wc_DownloadProgressChanged;
        wc.DownloadFileAsync (
            // Param1 = Link of file
            new System.Uri("http://www.sayka.com/downloads/front_view.jpg"),
            // Param2 = Path to save
            "D:\\Images\\front_view.jpg"
        );
    }
}
// Event to track the progress
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    progressBar.Value = e.ProgressPercentage;
}

14
A pergunta pede a maneira mais simples. Tornar mais complicado não é o mais simples.
Enigmatividade

75
A maioria das pessoas prefere uma barra de progresso durante o download. Então, eu apenas escrevi a maneira mais simples de fazer isso. Essa pode não ser a resposta, mas atende aos requisitos do Stackoverflow. Isso é ajudar alguém.
Sayka

3
Isso é tão simples quanto a outra resposta, se você simplesmente deixar de fora a barra de progresso. Esta resposta também inclui o espaço para nome e usa async para E / S. Além disso, a pergunta não pede a maneira mais simples, apenas uma maneira simples. :)
Josh

Eu acho que dar 2 respostas uma simples e outra com uma barra de progresso seria melhor
Jesse de gans

@Jessedegans Já existe uma resposta que mostra como simplesmente fazer o download sem uma barra de progresso. Foi por isso que escrevi uma resposta que ajuda no download assíncrono e na implementação da
barra de

76

Use System.Net.WebClient.DownloadFile:

string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;

// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
    myStringWebResource = remoteUri + fileName;
    // Download the Web resource and save it into the current filesystem folder.
    myWebClient.DownloadFile(myStringWebResource, fileName);        
}

42
using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");

33
Bem-vindo ao SO! Geralmente, não é uma boa ideia postar uma resposta de baixa qualidade para uma pergunta antiga e existente que já tenha respostas altamente votadas.
ThiefMaster

28
Encontrei minha resposta no comentário de seanb, mas realmente prefiro essa resposta de "baixa qualidade" que as outras. É completo (usando a declaração), conciso e fácil de entender. Ser uma pergunta antiga é irrelevante, IMHO.
30513 Josh

21
Mas acho que a resposta com o uso é muito melhor, porque acho que o WebClient deve ser descartado após o uso. Colocá-lo no interior usando garante que ele seja descartado.
Ricardo Polo Jaramillo

5
Não tem nada a ver com dispor neste exemplo de código ... A instrução usando aqui apenas mostrar o namespace de usar, sem que WebClient é o uso em usar a ser dispor ...
CDIE

17

Classe completa para baixar um arquivo enquanto imprime o status no console.

using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;

class FileDownloader
{
    private readonly string _url;
    private readonly string _fullPathWhereToSave;
    private bool _result = false;
    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);

    public FileDownloader(string url, string fullPathWhereToSave)
    {
        if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
        if (string.IsNullOrEmpty(fullPathWhereToSave)) throw new ArgumentNullException("fullPathWhereToSave");

        this._url = url;
        this._fullPathWhereToSave = fullPathWhereToSave;
    }

    public bool StartDownload(int timeout)
    {
        try
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_fullPathWhereToSave));

            if (File.Exists(_fullPathWhereToSave))
            {
                File.Delete(_fullPathWhereToSave);
            }
            using (WebClient client = new WebClient())
            {
                var ur = new Uri(_url);
                // client.Credentials = new NetworkCredential("username", "password");
                client.DownloadProgressChanged += WebClientDownloadProgressChanged;
                client.DownloadFileCompleted += WebClientDownloadCompleted;
                Console.WriteLine(@"Downloading file:");
                client.DownloadFileAsync(ur, _fullPathWhereToSave);
                _semaphore.Wait(timeout);
                return _result && File.Exists(_fullPathWhereToSave);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Was not able to download file!");
            Console.Write(e);
            return false;
        }
        finally
        {
            this._semaphore.Dispose();
        }
    }

    private void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        Console.Write("\r     -->    {0}%.", e.ProgressPercentage);
    }

    private void WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs args)
    {
        _result = !args.Cancelled;
        if (!_result)
        {
            Console.Write(args.Error.ToString());
        }
        Console.WriteLine(Environment.NewLine + "Download finished!");
        _semaphore.Release();
    }

    public static bool DownloadFile(string url, string fullPathWhereToSave, int timeoutInMilliSec)
    {
        return new FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec);
    }
}

Uso:

static void Main(string[] args)
{
    var success = FileDownloader.DownloadFile(fileUrl, fullPathWhereToSave, timeoutInMilliSec);
    Console.WriteLine("Done  - success: " + success);
    Console.ReadLine();
}

11
Por favor, você poderia explicar por que você está usando SemaphoreSlimneste contexto?
mmushtaq

10

Tente usar isto:

private void downloadFile(string url)
{
     string file = System.IO.Path.GetFileName(url);
     WebClient cln = new WebClient();
     cln.DownloadFile(url, file);
}

onde o arquivo será salvo?
IB

O arquivo será salvo no local onde está o arquivo executável. Se você quiser caminho completo, em seguida, usar o caminho completo, juntamente com o arquivo (que é o nome do item a ser baixado)
Surendra Shrestha

9

Além disso, você pode usar o método DownloadFileAsync na classe WebClient. Ele baixa para um arquivo local o recurso com o URI especificado. Além disso, esse método não bloqueia o segmento de chamada.

Amostra:

    webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");

Para maiores informações:

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/


8

Verifique se há uma conexão de rede usando GetIsNetworkAvailable()para evitar a criação de arquivos vazios quando não estiver conectado a uma rede.

if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
    using (System.Net.WebClient client = new System.Net.WebClient())
    {                        
          client.DownloadFileAsync(new Uri("http://www.examplesite.com/test.txt"),
          "D:\\test.txt");
    }                  
}

Eu sugeriria não usar GetIsNetworkAvailable(), pois, na minha experiência, retorna muitos falsos positivos.
Cherona em 21/01

A menos que você esteja em uma rede de computadores, como uma LAN, GetIsNetworkAvailable()sempre retornará corretamente. Nesse caso, você pode usar o System.Net.WebClient().OpenRead(Uri)método para verificar se ele retorna quando recebe um URL padrão. Veja WebClient.OpenRead ()
haZya em 21/01

2

O código abaixo contém lógica para o arquivo de download com nome original

private string DownloadFile(string url)
    {

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        string filename = "";
        string destinationpath = Environment;
        if (!Directory.Exists(destinationpath))
        {
            Directory.CreateDirectory(destinationpath);
        }
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result)
        {
            string path = response.Headers["Content-Disposition"];
            if (string.IsNullOrWhiteSpace(path))
            {
                var uri = new Uri(url);
                filename = Path.GetFileName(uri.LocalPath);
            }
            else
            {
                ContentDisposition contentDisposition = new ContentDisposition(path);
                filename = contentDisposition.FileName;

            }

            var responseStream = response.GetResponseStream();
            using (var fileStream = File.Create(System.IO.Path.Combine(destinationpath, filename)))
            {
                responseStream.CopyTo(fileStream);
            }
        }

        return Path.Combine(destinationpath, filename);
    }

1

Pode ser necessário conhecer o status e atualizar uma ProgressBar durante o download do arquivo ou usar credenciais antes de fazer a solicitação.

Aqui está, um exemplo que cobre essas opções. A notação Lambda e a interpolação de String foram usadas:

using System.Net;
// ...

using (WebClient client = new WebClient()) {
    Uri ur = new Uri("http://remotehost.do/images/img.jpg");

    //client.Credentials = new NetworkCredential("username", "password");
    String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
    client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";

    client.DownloadProgressChanged += (o, e) =>
    {
        Console.WriteLine($"Download status: {e.ProgressPercentage}%.");

        // updating the UI
        Dispatcher.Invoke(() => {
            progressBar.Value = e.ProgressPercentage;
        });
    };

    client.DownloadDataCompleted += (o, e) => 
    {
        Console.WriteLine("Download finished!");
    };

    client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}

1

Conforme minha pesquisa, descobri que WebClient.DownloadFileAsyncé a melhor maneira de baixar arquivos. Está disponível no System.Netespaço para nome e também suporta o núcleo .net.

Aqui está o código de exemplo para baixar o arquivo.

using System;
using System.IO;
using System.Net;
using System.ComponentModel;

public class Program
{
    public static void Main()
    {
        new Program().Download("ftp://localhost/test.zip");
    }
    public void Download(string remoteUri)
    {
        string FilePath = Directory.GetCurrentDirectory() + "/tepdownload/" + Path.GetFileName(remoteUri); // path where download file to be saved, with filename, here I have taken file name from supplied remote url
        using (WebClient client = new WebClient())
        {
            try
            {
                if (!Directory.Exists("tepdownload"))
                {
                    Directory.CreateDirectory("tepdownload");
                }
                Uri uri = new Uri(remoteUri);
                //password username of your file server eg. ftp username and password
                client.Credentials = new NetworkCredential("username", "password");
                //delegate method, which will be called after file download has been complete.
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(Extract);
                //delegate method for progress notification handler.
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgessChanged);
                // uri is the remote url where filed needs to be downloaded, and FilePath is the location where file to be saved
                client.DownloadFileAsync(uri, FilePath);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
    public void Extract(object sender, AsyncCompletedEventArgs e)
    {
        Console.WriteLine("File has been downloaded.");
    }
    public void ProgessChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
    }
}

Com o código acima, o arquivo será baixado dentro da tepdownloadpasta do diretório do projeto. Leia o comentário no código para entender o que o código acima faz.

Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.