[英]How Can I get the real name of an image from a url
我有下一個 url 關於圖像:
https://i.discogs.com/HE17wcv1sG6NDK1WcVyoQjSqUGDZva3SYvm6vXoCMOo/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTk2OTY5/NjktMTQ4NDkzNzkw/Ni00MDcyLmpwZWc.jpeg
如果我用導航器打開 url,然后按 de 右鍵將此圖像保存在我的硬盤中,導航器為該文件圖像解析的名稱是不同的。 如何獲取 c# 中文件的姓氏?
如果您准備使用WebClient
,則可以將數據下載到 memory,檢查 Content-Disposition header,然后相應地更改文件名。 如果您異步使用此方法,我已經添加了注釋掉的部分,您可以使用這些部分來代替它們的同步對應部分。
// private static async Task DownloadImageAsync(string url, string folder)
private static void DownloadImage(string url, string folder)
{
var uri = new Uri(url);
string fileName = Path.GetFileName(uri.AbsolutePath);
WebClient client = new WebClient();
// byte[] fileData = await client.DownloadDataTaskAsync(url);
byte[] fileData = client.DownloadData(url);
string disposition = client.ResponseHeaders.Get("Content-Disposition"); // try to get the disposition
if (!string.IsNullOrEmpty(disposition) // check it has a value
&& ContentDispositionHeaderValue.TryParse(disposition, out var parsedDisposition) // check it can be parsed
&& !string.IsNullOrEmpty(parsedDisposition.FileName)) // check a filename is specified
{
fileName = parsedDisposition.FileName.Trim('"'); // replace the normal filename with the parsed one
}
// await File.WriteAllBytesAsync(Path.Combine(folder, fileName), fileData);
File.WriteAllBytes(Path.Combine(folder, fileName), fileData);
}
用法: DownloadImage(myurl, @"C:\Users\Me\Desktop");
也就是說, WebClient
有點過時,您可能應該使用HttpClient
進行較新的開發:
private static async Task DownloadImageAsync(string url, string folder)
{
var uri = new Uri(url);
string fileName = Path.GetFileName(uri.AbsolutePath);
using var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
if (!string.IsNullOrEmpty(response.Content.Headers.ContentDisposition?.FileName))
{
fileName = response.Content.Headers.ContentDisposition.FileName.Trim('"');
}
using var outputFile = File.Create(Path.Combine(folder, fileName));
await response.Content.CopyToAsync(outputFile);
}
用法: await DownloadImageAsync(myurl, @"C:\Users\Me\Desktop");
Microsoft 建議在整個應用程序 ( docs ) 中使用HttpClient
的單個 static 實例。 但這確實有缺陷,因此根據您的應用程序,您可能需要研究使用IHttpClientFactory ,它可以解決使用 static HttpClient
所帶來的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.