繁体   English   中英

获取不带内容处置的文件名

[英]Get filename without Content-Disposition

我几天来一直在寻找解决这个问题的方法,但找不到。

我想使用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)下载文件,文件名将显示在文件对话框中,因此必须将其保存在某个地方。

您能想象在哪里可以找到它吗?

编辑:我不能从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 { }

http://upload.p-kratzer.com/index.php?dir=&file=asdfasdfwervdcvvedb上进行了测试,它确实返回wetter.JPG。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM