当文件类型和文件名未知时,通过url下载c#中的文件

时间:2015-04-27 13:32:34

标签: c# asp.net

这与How to download a file from a URL in C#?有关但在我的情况下,网址没有包含在网址中的文件名。假设一个网址www.test.com/files0是一个文件,在浏览器中它被下载为123.mpg如何将它保存在具有相同名称和扩展名的服务器上?

基本上,我想在从url下载文件之前获取文件名和类型,并且只有在允许的扩展名下才下载文件。

1 个答案:

答案 0 :(得分:4)

假设您使用HttpClient类发出请求,可以使用查询返回的HttpResponseMessage来决定是否要下载文件。例如:

HttpClient client = new HttpClient();

HttpResponseMessage response = await client.GetAsync("http://MySite/my/download/path").ConfigureAwait(false);

if (!String.Equals(response.Content.Headers.ContentDisposition.DispositionType, "attachment", StringComparison.OrdinalIgnoreCase)) {
  return;
}

// Call some method that will check if the file extension and/or media type 
// of the file are acceptable.
if (!IsAllowedDownload(response.Content.Headers.ContentDisposition.FileName, response.Content.Headers.ContentType.MediaType)) {
  return;
}

// Call some method that will take a stream containing the response payload 
// and write it somewhere.
WriteResponseStream(await response.Content.ReadAsStreamAsync().ConfigureAwait(false));