28

In .Net 4.0 I used WebClient to download files from an url and save them on my local drive. But I am not able to achieve the same in .Net Core.

Can anyone help me out on this?

jAC
  • 5,195
  • 6
  • 40
  • 55
Ravi
  • 326
  • 1
  • 4
  • 10
  • Are you sure asp.net-core-mvc is the right tag? From your question it seems you're talking about client software. Either way: Use `HttpClient` if you want to download files. – jAC Aug 30 '17 at 11:55

3 Answers3

39

WebClient is not available in .NET Core. (UPDATE: It is from 2.0) The usage of HttpClient in the System.Net.Http is therefore mandatory:

using System.Net.Http;
using System.Threading.Tasks;
...
public static async Task<byte[]> DownloadFile(string url)
{
    using (var client = new HttpClient())
    {

        using (var result = await client.GetAsync(url))
        {
            if (result.IsSuccessStatusCode)
            {
                return await result.Content.ReadAsByteArrayAsync();
            }

        }
    }
    return null;
}
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206
jAC
  • 5,195
  • 6
  • 40
  • 55
  • 14
    For readers, be aware that you shouldn't use HttpClient this way. An option is to let HttpClientFactory handle the lifetime of an Httpclient object. Read [more](https://stackoverflow.com/questions/50912160/should-httpclient-instances-created-by-httpclientfactory-be-disposed) – Kristianne Nerona Aug 06 '19 at 00:47
24

WebClient is available from .net core 2.0

var wc = new System.Net.WebClient();
wc.DownloadFile( URL, @"c:\temp\myfile.txt");
Eduardo Molteni
  • 38,786
  • 23
  • 141
  • 206
6

In NetCore 6.0, you should use HttpClient instead of WebClient which is obsolete, and you have the async methods in the new File class.

The implementation is simple as the following:

static async Task DownloadFile(string url, string pathToSave, string fileName)
{
    var content = await GetUrlContent(url);
    if (content != null)
    {
        if (!Directory.Exists(pathToSave)) Directory.CreateDirectory(pathToSave);
        await File.WriteAllBytesAsync($"{pathToSave}/{fileName}", content);
    }
}

static async Task<byte[]?> GetUrlContent(string url)
{
    using (var client = new HttpClient())
    using (var result = await client.GetAsync(url))
        return result.IsSuccessStatusCode ? await result.Content.ReadAsByteArrayAsync():null;
}

Usage:

await DownloadFile("https://exampl.com/image.jpg", @"c:\DownloadedImages", "image.jpg");
Ester Kaufman
  • 708
  • 10
  • 20
  • 3
    This answer is nearly perfect, however it's generally not considered best practice to instantiate HttpClient using the constructor directly unless you are certain you will only do this once in the application lifetime. Better to construct a singleton to be reused or use IHttpClientFactory (personal favorite). More info here: https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/httpclient-guidelines – Luke Jun 29 '22 at 14:01