将文件从url下载到.Net Core中的本地设备

将文件从url下载到.Net Core中的本地设备

问题描述:

在.Net 4.0中,我使用WebClient从URL下载文件并将其保存在本地驱动器上。但是我无法在.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.

有人可以帮我吗?

WebClient .NET Core 中不可用。 (更新:它来自 2.0 )因此必须在 System.Net.Http 中使用 HttpClient

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