2013-12-10 124 views
13

當Uri不包含名稱時,有什麼方法可以知道使用WebClient下載的文件的原始名稱?使用WebClient下載時獲取原始文件名

這種情況發生在下載源自動態頁面的地方,其中名稱未知。

使用我的瀏覽器,該文件獲取正確的名稱。但是,如何使用WebClient完成這項工作? 例如

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

使用DownloadFile()不是解決方案,因爲此方法需要預先指定文件名。

+3

你有沒有試過檢查'wc.ResponseHeaders'?文件下載通常包含帶有文件名的附件頭。 – Tobberoth

+0

Tobberoth。這的確是答案!不知道。非常非常感謝你! –

回答

27

您需要檢查響應頭,看看是否有是一個包含實際文件名的內容處置頭。

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

'System.Net.Mime.ContentDisposition'可以用來解析頭文件'var header = new ContentDisposition(wc.ResponseHeaders [「Content-Disposition」]);' –

+2

謝謝,但正確的是「.... IndexOf(「filename =」)+ 9)....「 –

+0

@RaphaelZimermann你是對的。更新了我的答案。謝謝。 – HaukurHaf

5

讀取響應頭"Content-Disposition"WebClient.ResponseHeaders

它應該是:

Content-Disposition: attachment; filename="fname.ext" 

你的代碼應該是這樣的:

string header = wc.ResponseHeaders["Content-Disposition"]??string.Empty; 
const string filename="filename="; 
int index = header.LastIndexOf(filename,StringComparison.OrdinalIgnoreCase); 
if (index > -1) 
{ 
    fileName = header.Substring(index+filename.Length); 
} 
+1

很好的答案,但索引需要提前考慮「filename =」的長度。恕我直言,我會改變它爲fileName = header.Substring(索引+「文件名=」。長度); – pbarranis

+2

@pbarranis你說得對,更正了! – giammin