使用 WebClient 下载时获取原始文件名 [英] Get original filename when downloading with WebClient

查看:72
本文介绍了使用 WebClient 下载时获取原始文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当 Uri 不包含名称时,有没有办法知道您使用 WebClient 下载的文件的原始名称?

Is there any way to know the original name of a file you download using the WebClient when the Uri doesn't contain the name?

这种情况发生在例如下载源自动态页面的站点中,而该页面的名称事先未知.

This happens for example in sites where the download originates from a dynamic page where the name isn't known beforehand.

使用我的浏览器,文件得到正确的名称.但是如何使用 WebClient 做到这一点呢?例如

Using my browser, the file gets the orrect name. But how can this be done using the WebClient? E.g.

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

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

Using DownloadFile() isn't a solution since this method needs a filename in advance.

推荐答案

您需要检查响应标头,看看是否存在包含实际文件名的 content-disposition 标头.

You need to examine the response headers and see if there is a content-disposition header present which includes the actual filename.

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("\"", "");
}

这篇关于使用 WebClient 下载时获取原始文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆