2013-12-10 5 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

トバベロス。それは本当に答えです!それを知らなかった。本当にありがとう! –

答えて

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

それがあるべきWebClient.ResponseHeaders

とレスポンスヘッダー"Content-Disposition"を読む:

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 ="の長さを考慮してインデックスを拡張する必要があります。 IMHO私はそれをfileName = header.Substring(index + "filename ="。Length)に変更します。 – pbarranis

+2

@pbarranisあなたが正しく、修正されました! – giammin

関連する問題