提问人:Xlebuchek 提问时间:11/9/2023 最后编辑:Qiang FuXlebuchek 更新时间:11/13/2023 访问量:74
C# 从 URL 下载资源
C# Download Resources From URL
问:
我一直在 c# 上的浏览器上工作,我需要从 URL 下载所有文件。问题是并非所有文件都已下载。
我怀疑我的函数实现可能存在问题。有人可以帮我确定问题可能是什么并提出解决方案吗?
以下是我下载文件的代码片段:
public class ResourceManager
{
private readonly string _dataPath;
public ResourceManager(string dataPath)
{
this._dataPath = dataPath;
}
private Dictionary<string, Dictionary<string, string>> _data = new();
private static bool DownloadResource(string url, string path)
{
using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Get, url);
using var response = client.Send(request);
if (response.IsSuccessStatusCode)
{
using var fs = new FileStream(path, FileMode.OpenOrCreate);
response.Content.CopyToAsync(fs);
return true;
}
else
{
//Console.Error.WriteLine($"Bad Url: {url}");
return false;
}
}
public bool GetResource(string url, out string fileName)
{
var myUri = new Uri(url);
var host = myUri.Host;
var path = myUri.AbsolutePath;
if (!_data.ContainsKey(host))
{
_data.Add(host, new Dictionary<string, string>());
}
_data[host].TryGetValue(path, out fileName);
if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName)) return true;
fileName = Path.Combine(_dataPath, $"{host}__{Util.ComputeHash(path)}");
if (DownloadResource(url, fileName))
{
_data[host].Add(path, fileName);
return true;
}
else
{
fileName = null;
return false;
}
}
}
答:
0赞
Qiang Fu
11/13/2023
#1
Httpclient 无法从 URL 获取所有资源。我建议您尝试使用“httrack”https://www.httrack.com/page/2/#google_vignette 将网站资源抓取到本地文件夹。抓取后,您可以离线浏览网站。
评论
StreamCopyToAsync
(顾名思义)是一种异步方法。虽然你可以这样称呼它,但你永远不会(a)等待它的结果。您应该熟悉从 URL 获取数据时。async
await