Upload files from url to local device in .Net Core

In .Net 4.0, I used WebClient to download files from a URL and save them to my local drive. But I can not achieve the same in .Net Core.

Can someone help me with this?

+4
source share
2 answers

WebClientunavailable at .NET Core. Therefore, the use HttpClientof System.Net.Httpis 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;
}
+6
source

You can use HttpClientfrom System.Net.Http. I recommend using .NET Core 2.0.

 public async Task<bool> Download()
 {
      var client = new HttpClient();

      var response = await client.GetAsync("https://github.com/twbs/bootstrap/releases/download/v4.0.0-beta/bootstrap-4.0.0-beta-dist.zip");

      using(var fs = new FileStream(@"c:\_data\bootstrap-4.0.0-beta-dist.zip", FileMode.Create))
      {
           await response.Content.ReadAsStreamAsync().Result.CopyToAsync(fs);
      }

      return true;
 }
-1
source

Source: https://habr.com/ru/post/1684736/


All Articles