2012-11-02 75 views
2

我可以从格式化这样的URL访问的服务器上的文件: HTTP://地址/ Attachments.aspx ID = GUID如何:在C#中下载保留原始名称的文件?

我有机会获得GUID,需要能够下载多个文件到同一个文件夹。

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

我想在C#中复制该行为。我尝试过使用WebClient类的DownloadFile方法,但是必须指定一个新的文件名。更糟糕的是,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));    
    } 

只是不得不做一些字符串操作来获得实际文件名。我太激动了。感谢大家!

+0

。 –

+6

@HansPassant:否;他只需要解析“Content-Disposition”。 – SLaks

+2

您不必手动解析Content-Disposition标头,.NET有一个类来执行此操作('System.Net.Mime.ContentDisposition') –

回答

5

正如在评论中暗示的那样,文件名将在Content-Disposition标头中可用。不知道如何使用WebClient时候能得到它的价值,但它是相当简单的用WebRequest:如果你想原始文件名,那么你需要一个不同类型的服务器,FTP服务器

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

您不必手动解析Content-Disposition标头。 NET有一个类来做到这一点('System.Net.Mime.ContentDisposition') –

+0

我试过了,我从这个链接是null https://www.gravatar.com/avatar/0e4377279c8f5d9e53cf807ab3f9f717?s=32&d=identicon&r=PG – Mortalus

相关问题