将文件从url下载到.Net Core中的本地设备 [英] Download files from url to local device in .Net Core

查看:751
本文介绍了将文件从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;
}

这篇关于将文件从url下载到.Net Core中的本地设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆