有人可以帮我把这个代码段转换成它的.net核心等价物吗?
Uri uri = new Uri(url);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
string extension = Path.GetExtension(filename);
string tempFilepath = Path.GetTempFileName() + extension;
try
{
WebClient webClient = new WebClient();
webClient.DownloadFile(url, tempFilepath);
if (new FileInfo(tempFilepath).Length > 0)
{
return tempFilepath;
}
else {
return null;
}
}
catch (WebException e)
{
return null;
}
catch (NotSupportedException e)
{
return null;
}
实际上,此代码以前是在.net 4.6中写入的应用程序中。然后前段时间,我们停止使用该应用程序。现在我正在开发.net核心中的另一个应用程序,并将做同样的事情。所以我想知道如何使用.net核心这样做? HttpClient中DownloadFile方法的替代方法是什么?
答案 0 :(得分:3)
这个应该这样做......
try
{
using (var client = new HttpClient())
{
using (HttpResponseMessage response = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).Result)
{
response.EnsureSuccessStatusCode();
using (Stream contentStream = response.Content.ReadAsStreamAsync().Result, fileStream = new FileStream(tempFilepath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
var buffer = new byte[8192];
var isMoreToRead = true;
do
{
var read = contentStream.ReadAsync(buffer, 0, buffer.Length).Result;
if (read == 0)
{
isMoreToRead = false;
}
else
{
fileStream.WriteAsync(buffer, 0, read);
}
}
while (isMoreToRead);
}
}
}
或者您可以更加干净地实现这一点:How to implement progress reporting for Portable HttpClient
答案 1 :(得分:0)
更简单的做法是......
HttpClient client = new HttpClient();
try
{
var response = client.GetStringAsync(url);
Console.WriteLine(response.Result);
}
catch (Exception e)
{
Console.WriteLine("Message :{0} ", e.Message);
}
finally{
client.Dispose();
}
目标框架: netcoreapp1.1
编辑: Visual Studio代码
应用类型:控制台应用