Rav*_*avi 14 c# .net-core asp.net-core
在.Net 4.0中,我使用WebClient从URL下载文件并将其保存在本地驱动器上.但是我无法在.Net Core中实现相同的功能.
任何人都可以帮我解决这个问题吗?
jAC*_*jAC 21
WebClient不可用.NET Core.(UPDATE:它是从2.0)的使用HttpClient在System.Net.Http因此强制性:
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;
}
Run Code Online (Sandbox Code Playgroud)
小智 8
在NetCore 6.0中,您应该使用已过时的HttpClient代替WebClient,并且您在新类中拥有异步方法File。
实现简单如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
用法:
await DownloadFile("https://exampl.com/image.jpg", @"c:\DownloadedImages", "image.jpg");
Run Code Online (Sandbox Code Playgroud)
WebClient可从.net core 2.0获得
var wc = new System.Net.WebClient();
wc.DownloadFile( URL, @"c:\temp\myfile.txt");
Run Code Online (Sandbox Code Playgroud)