我正在寻找这个问题的解决方案好几天,我找不到任何.
我想从带有webclient的web服务器下载文件.下载工作正常,但我无法获得真正的文件名,这对我来说非常重要.
我在许多主页上看过,文件名应该保存在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)下载文件,文件名将显示在filedialog中,因此必须将其保存在某处.
你能想象我能在哪里找到它吗?
- 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 { }
在http://upload.p-kratzer.com/index.php?dir=&file=asdfasdfwervdcvvedb上进行了测试,确实返回了wetter.JPG.