当Uri不包含名称时,有没有办法知道使用WebClient下载的文件的原始名称?
例如,在下载源自事先不知道名称的动态页面的站点中会发生这种情况。
使用我的浏览器,文件获得正确的名称。但是如何使用WebClient完成这项工作? E.g。
WebClient wc= new WebClient();
var data= wc.DownloadData(@"www.sometime.com\getfile?id=123");
使用DownloadFile()不是解决方案,因为此方法需要提前输入文件名。
答案 0 :(得分:31)
您需要检查响应标头,看看是否存在包含实际文件名的内容处置标头。
WebClient wc = new WebClient();
var data= wc.DownloadData(@"www.sometime.com\getfile?id=123");
string fileName = "";
// Try to extract the filename from the Content-Disposition header
if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
{
fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 9).Replace("\"", "");
}
答案 1 :(得分:6)
"Content-Disposition"
应该是:
Content-Disposition: attachment; filename="fname.ext"
您的代码应如下所示:
string header = wc.ResponseHeaders["Content-Disposition"]??string.Empty;
const string filename="filename=";
int index = header.LastIndexOf(filename,StringComparison.OrdinalIgnoreCase);
if (index > -1)
{
fileName = header.Substring(index+filename.Length);
}
答案 2 :(得分:1)
要获取文件名而不下载文件:
public string GetFilenameFromWebServer(string url)
{
string result = "";
var req = System.Net.WebRequest.Create(url);
req.Method = "HEAD";
using (System.Net.WebResponse resp = req.GetResponse())
{
// Try to extract the filename from the Content-Disposition header
if (!string.IsNullOrEmpty(resp.Headers["Content-Disposition"]))
{
result = resp.Headers["Content-Disposition"].Substring(resp.Headers["Content-Disposition"].IndexOf("filename=") + 9).Replace("\"", "");
}
}
return result;
}
答案 3 :(得分:0)
如果您和我一样,必须处理Content-Disposition标头,该标头格式不正确或者由于某种原因无法由ContentDisposition类自动解析,这是我的解决方案:
string fileName = null;
// Getting file name
var request = WebRequest.Create(url);
request.Method = "HEAD";
using (var response = request.GetResponse())
{
// Headers are not correct... So we need to parse manually
var contentDisposition = response.Headers["Content-Disposition"];
// We delete everything up to and including 'Filename="'
var fileNameMarker= "filename=\"";
var beginIndex = contentDisposition.ToLower().IndexOf(fileNameMarker);
contentDisposition = contentDisposition.Substring(beginIndex + fileNameMarker.Length);
//We only get the string until the next double quote
var fileNameLength = contentDisposition.ToLower().IndexOf("\"");
fileName = contentDisposition.Substring(0, fileNameLength);
}