获取没有Content-Disposition的文件名

时间:2012-11-26 18:23:14

标签: c# header webclient content-disposition

我正在寻找这个问题的解决方案好几天,我找不到。

我想从带有webclient的网络服务器下载文件。下载工作正常,但我无法获得真正的文件名,这对我来说非常重要。

我在许多主页上看过,文件名应该保存在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中,因此必须将其保存在某处。

你能想象我能在哪里找到它吗?

编辑:我无法从URL中提取它,因为链接是由php生成的

http://www.example.com/download.php?id=10

1 个答案:

答案 0 :(得分:15)

你可以试试这个:

        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。

相关问题