c# - 如何 : download a file keeping the original name in C#?

标签 c# download webclient

我在服务器上有文件,可以通过格式如下的 URL 访问: http://地址/Attachments.aspx?id=GUID

我可以访问 GUID,并且需要能够将多个文件下载到同一个文件夹。

如果您获取该 URL 并将其放入浏览器,您将下载该文件,并且它将具有原始文件名。

我想在 C# 中复制该行为。我试过使用 WebClient 类的 DownloadFile 方法,但是你必须指定一个新的文件名。更糟糕的是,下载文件会覆盖现有文件。我知道我可以为每个文件生成一个唯一的名称,但我真的很喜欢原来的名称。

是否可以下载保留原始文件名的文件?

更新:

使用下面的奇妙答案来使用 WebReqest 类,我想出了以下完美的方法:

    public override void OnAttachmentSaved(string filePath)
    {
        var webClient = new WebClient();

        //get file name
        var request = WebRequest.Create(filePath);
        var response = request.GetResponse();
        var contentDisposition = response.Headers["Content-Disposition"];
        const string contentFileNamePortion = "filename=";
        var fileNameStartIndex = contentDisposition.IndexOf(contentFileNamePortion, StringComparison.InvariantCulture) + contentFileNamePortion.Length;
        var originalFileNameLength = contentDisposition.Length - fileNameStartIndex;
        var originalFileName = contentDisposition.Substring(fileNameStartIndex, originalFileNameLength);

        //download file
        webClient.UseDefaultCredentials = true;
        webClient.DownloadFile(filePath, String.Format(@"C:\inetpub\Attachments Test\{0}", originalFileName));            
    }

只需要做一些字符串操作就可以得到实际的文件名。我太激动了。谢谢大家!

最佳答案

正如评论中所暗示的,文件名将在 Content-Disposition header 中可用。不确定在使用 WebClient 时如何获取它的值,但使用 WebRequest 时相当简单:

WebRequest request = WebRequest.Create("http://address/Attachments.aspx?id=GUID");
WebResponse response = request.GetResponse();
string originalFileName = response.Headers["Content-Disposition"];
Stream streamWithFileBody = response.GetResponseStream();

关于c# - 如何 : download a file keeping the original name in C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13201059/

相关文章:

c# - 将授权属性与 Azure Active Directory 结合使用

c# - 在asp.net中调用方法时传递字符串参数

php - Firefox 将 .zip 文件下载(尝试打开)为 .HTM

c# - 打开 App 时不显示 PUSH

C# 和 PHP 的 AES 加密结果不同

Python Mechanize 检测下载的文件扩展名

java - 为什么有很多框架支持多次上传,但没有一个支持多次下载?

spring - 如何将 Mono<String> 转换为 Mono<MyObject>?

c# - 如何检查 WebClient 请求是否有 404 错误

wpf - 从 WPF 应用程序验证 ASP.NET MVC 用户