【问题标题】:Get original filename when downloading with WebClient使用 WebClient 下载时获取原始文件名
【发布时间】:2013-12-27 20:16:58
【问题描述】:

当 Uri 不包含名称时,有什么方法可以知道您使用 WebClient 下载的文件的原始名称?

例如,在下载源自事先不知道名称的动态页面的网站中,就会发生这种情况。

使用我的浏览器,文件会得到正确的名称。但是如何使用 WebClient 来完成呢? 例如

        WebClient wc= new WebClient();
        var data=   wc.DownloadData(@"www.sometime.com\getfile?id=123");

使用 DownloadFile() 不是一个解决方案,因为此方法需要提前指定文件名。

【问题讨论】:

  • 你试过检查wc.ResponseHeaders吗?文件下载通常包含带有文件名的附件标题。
  • 托伯罗斯。这确实是答案!不知道那个。非常非常感谢!
  • 一些从动态页面下载的站点会生成重定向,并且不会在重定向响应上设置“Content-Disposition”,因此您可以使用 HttpClient with AutoRedirect=false,使用 HEAD 方法然后获取响应中的“位置”标头。

标签: c# .net webclient


【解决方案1】:

您需要检查响应标头并查看是否存在包含实际文件名的内容处置标头。

WebClient wc = new WebClient();
var data=   wc.DownloadData(@"www.sometime.com\getfile?id=123");
string fileName = "";

// Try to extract the filename from the Content-Disposition header
if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
{
 fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 9).Replace("\"", "");
}

【讨论】:

  • System.Net.Mime.ContentDisposition可以用来解析头部var header = new ContentDisposition(wc.ResponseHeaders["Content-Disposition"]);
【解决方案2】:

使用WebClient.ResponseHeaders 读取响应标头"Content-Disposition"

应该是:

    Content-Disposition: attachment; filename="fname.ext"

您的代码应如下所示:

string header = wc.ResponseHeaders["Content-Disposition"]??string.Empty;
const string filename="filename=";
int index = header.LastIndexOf(filename,StringComparison.OrdinalIgnoreCase);
if (index > -1)
{
    fileName = header.Substring(index+filename.Length);
}

【讨论】:

  • 很好的答案,但索引需要提前考虑“文件名=”的长度。恕我直言,我将其更改为 fileName = header.Substring(index + "filename=".Length);
【解决方案3】:

在不下载文件的情况下获取文件名:

public string GetFilenameFromWebServer(string url)
{
    string result = "";

    var req = System.Net.WebRequest.Create(url);
    req.Method = "HEAD";
    using (System.Net.WebResponse resp = req.GetResponse())
    {
        // Try to extract the filename from the Content-Disposition header
        if (!string.IsNullOrEmpty(resp.Headers["Content-Disposition"]))
        {
            result = resp.Headers["Content-Disposition"].Substring(resp.Headers["Content-Disposition"].IndexOf("filename=") + 9).Replace("\"", "");
        }
    }

    return result;
}

【讨论】:

    【解决方案4】:

    如果您和我一样,必须处理格式不正确或由于某种原因无法由 ContentDisposition 类自动解析的 Content-Disposition 标头,这是我的解决方案:

    string fileName = null;
    
    // Getting file name
    var request = WebRequest.Create(url);
    request.Method = "HEAD";
    
    using (var response = request.GetResponse())
    {
        // Headers are not correct... So we need to parse manually
        var contentDisposition = response.Headers["Content-Disposition"];
    
        // We delete everything up to and including 'Filename="'
        var fileNameMarker= "filename=\"";
        var beginIndex = contentDisposition.ToLower().IndexOf(fileNameMarker);
        contentDisposition = contentDisposition.Substring(beginIndex + fileNameMarker.Length);
    
        //We only get the string until the next double quote
        var fileNameLength = contentDisposition.ToLower().IndexOf("\"");
        fileName = contentDisposition.Substring(0, fileNameLength);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-18
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      相关资源
      最近更新 更多