c# - 使用 WebClient 下载时获取原始文件名

标签 c# .net webclient

当 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/

相关文章:

c# - 并行运行时 IronPDF 死锁

c# - (为什么/如何)我应该使用 .designer 文件?

.net - linq to sql和 Entity Framework 的区别

c# - Webclient 没有得到响应 uri

c# - 我如何选择绘制的矩形并在面板中清除它?

c# - TreeNode.Nodes.ContainsKey 的算法是什么

c# - 是否可以通过内存映射文件将实例 "pointer"传递给另一个进程?

.net - 如果字符串为空,我应该抛出 ArgumentNullException 吗?

.net - WebClient 与代理设置 - 或下载加速器的乐趣

c# - 网页有时无法使用 SSL 连接到其他 url