当 Uri 不包含名称时,有什么方法可以知道您使用 WebClient 下载的文件的原始名称?
例如,这种情况发生在下载源自事先不知道名称的动态页面的站点中。
使用我的浏览器,文件获得了正确的名称。但是如何使用 WebClient 来完成呢? 例如
WebClient wc= new WebClient();
var data= wc.DownloadData(@"www.sometime.com\getfile?id=123");
使用 DownloadFile() 不是解决方案,因为此方法需要提前提供文件名。
最佳答案
您需要检查响应 header 并查看是否存在包含实际文件名的内容配置 header 。
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("\"", "");
}
关于c# - 使用 WebClient 下载时获取原始文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20492355/