Download files from url to local device in .Net Core

前端 未结 2 1793
夕颜
夕颜 2020-12-31 00:23

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 ou

2条回答
  •  囚心锁ツ
    2020-12-31 01:20

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

提交回复
热议问题