通过URL下载在C#中的文件时,文件类型和文件名是未知 [英] Download a file in c# via url when file type and file name is unknown

查看:1517
本文介绍了通过URL下载在C#中的文件时,文件类型和文件名是未知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关系到如何下载文件在C#中的网址?但对我来说这么想的都包含在URL文件名的URL。假设URL www.test.com/files0是一个文件,并在它被下载为123.mpg浏览器我如何可以将它保存在服务器上使用相同的名称和延伸?

This is related to How to download a file from a URL in C#? but in my case the url dosen't have file name included in url. suppose a url www.test.com/files0 is a file and in the browser it gets downloaded as 123.mpg how can i save it on server with the same name and extention?

基本上,我想从以下网址下载文件之前得到的文件名和类型,只下载该文件,如果它是允许的扩展。

Basically, I want to get filename and type before downloading the file from url and only download the file if it is an allowed extension.

推荐答案

假设你使用的HttpClient 类,使您的要求,您可以使用的Htt presponseMessage 该查询返回来决定,如果你想下载的文件或没有。例如:

Assuming that you're using the HttpClient class to make your request, You can use the HttpResponseMessage that your query returns to decide if you want to download the file or not. For example:


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));

这篇关于通过URL下载在C#中的文件时,文件类型和文件名是未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆