我几天来一直在寻找这个问题的解决方案,但找不到任何解决方案。
我想使用网络客户端从网络服务器下载文件。下载工作正常,但我无法获得真实的文件名,这对我来说非常重要。
我在很多主页上看到,文件名应该保存在 Content-Disposition-Header 中。不幸的是,该网站的标题是空的。我试着用以下方法得到它:
string header_contentDisposition ="";
using (WebClient client = new WebClient())
{
client.OpenRead(link);
header_contentDisposition = client.ResponseHeaders["Content-Disposition"];
MessageBox.Show(header_contentDisposition);
}
此标头内没有保存任何信息。
如果我尝试使用浏览器(IE、Opera、Chrome)下载文件,文件名会显示在文件对话框中,因此必须将其保存在某个地方。
你能想象我在哪里可以找到它吗?
编辑:我无法从 URL 中提取它,因为该链接是由 php 生成的,例如
http://www.example.com/download.php?id=10
你可以试试这个:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
using (Stream rstream = res.GetResponseStream())
{
string fileName = res.Headers["Content-Disposition"] != null ?
res.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "") :
res.Headers["Location"] != null ? Path.GetFileName(res.Headers["Location"]) :
Path.GetFileName(url).Contains('?') || Path.GetFileName(url).Contains('=') ?
Path.GetFileName(res.ResponseUri.ToString()) : defaultFileName;
}
res.Close();
}
catch { }
对此进行了测试它确实返回wetter.JPG。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)