获取文件名,而不内容处置 [英] Get filename without Content-Disposition
问题描述
我要寻找这个问题的解决方案了几天,我找不到任何。
我想从一个Web客户端的网络服务器下载文件。下载工作正常,但我不能让真正的文件名,这对我来说是非常重要的。
我看了很多网页,该文件名应保存在内容处置标头。不幸的是,网站的这个头是空的。我试图得到它:
字符串header_contentDisposition =;
使用(Web客户端的客户端=新的WebClient())
{
client.OpenRead(链接);
header_contentDisposition = client.ResponseHeaders [内容处置];
MessageBox.Show(header_contentDisposition);
}
有没有保存这个头内的信息。
如果我尝试下载文件,我的浏览器(IE,歌剧,铬)的文件名被显示在FileDialog的,所以它在某处被保存。
$ 2 b $ b
你能想象我在哪里可以找到它。
编辑:我无法从URL中提取它,因为链接是通过像PHP产生
http://www.example.com/download.php?id=10
您可以试试这个:
HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(URL);
试
{
HttpWebResponse解析度=(HttpWebResponse)request.GetResponse();
使用(流rstream = res.GetResponseStream())
{
字符串文件名= res.Headers [内容处置]!= NULL?
res.Headers [内容处置]替换(附件;文件名=,).Replace(\,):
res.Headers [位置] = NULL Path.GetFileName(res.Headers [!?位置):
Path.GetFileName(URL)。载有('?')|| Path.GetFileName(URL)。载有('= ?')
Path.GetFileName(res.ResponseUri.ToString()):defaultFileName;
}
res.Close();
}
赶上{}
上的 http://upload.p-kratzer.com/index.php?dir=&file=asdfasdfwervdcvvedb ,它并返回wetter.JPG
。I am looking for a solution for this problem for days and I can't find any.
I want to download a file from a webserver with a webclient. The download works fine, but I can't get the real filename, which is very important for me.
I read on many homepages, that the filename should be saved in the Content-Disposition-Header. Unfortunately this header of the site is empty. I tried to get it with:
string header_contentDisposition ="";
using (WebClient client = new WebClient())
{
client.OpenRead(link);
header_contentDisposition = client.ResponseHeaders["Content-Disposition"];
MessageBox.Show(header_contentDisposition);
}
There is no information saved inside this header.
If I try to download the file with my Browser (IE, Opera, Chrome) the filename gets shown in the filedialog, so it has to be saved somewhere.
Can you imagine where I can find it?
EDIT: I can't extract it from the URL, because the link is generated by php like
http://www.example.com/download.php?id=10
You can try this:
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 { }
Tested this on http://upload.p-kratzer.com/index.php?dir=&file=asdfasdfwervdcvvedb and it does return wetter.JPG.
这篇关于获取文件名,而不内容处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!