Ravi
Ravi

Reputation: 326

Download files from url to local device in .Net Core

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?

Upvotes: 28

Views: 42755

Answers (3)

Ester Kaufman
Ester Kaufman

Reputation: 868

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");

Upvotes: 9

jAC
jAC

Reputation: 5324

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;
}

Upvotes: 39

Eduardo Molteni
Eduardo Molteni

Reputation: 39413

WebClient is available from .net core 2.0

var wc = new System.Net.WebClient();
wc.DownloadFile( URL, @"c:\temp\myfile.txt");

Upvotes: 24

Related Questions