2017-03-22 9 views
0
WebClient webClient = new WebClient(); 
webClient.DownloadFileAsync(new Uri(urlDownload), @"C:\Files\Test\Folder\test.txt"); 

私はフォルダにあるtest.txtファイルを保存したい場合は、私が前に(Files\Test\Folder)これらのフォルダを作成したとき、WebClientは、唯一のファイルを保存します。 しかし、たとえばTestというフォルダが作成されていない場合、Webclientは何も保存しません。どのようにWebClientが自動的にフォルダを追加できますか?

フォルダは自動的に追加されますか?

答えて

3

あなたはそれを作成し、必要なフォルダが既に存在しない場合は、最初のチェックする必要があり、ファイルの開始ダウンロードした後になります。

string path = "@C:\Files\Test\Folder"; 
string filePath = path +"\\test.txt"; 
if (!Directory.Exists(path)) 
{ 
    Directory.CreateDirectory(path); 
} 
WebClient webClient = new WebClient(); 
webClient.DownloadFileAsync(new Uri(urlDownload),filePath); 

より多くの、より良いメソッドを作成することです:

private void CreateFolder(string path) 
{ 
    if (!Directory.Exists(path)) 
    { 
     Directory.CreateDirectory(path); 
    } 
} 

とし、電話:

string path = "@C:\Files\Test\Folder"; 
string filePath = path +"\\test.txt"; 
CreateFolder(path); 
WebClient webClient = new WebClient(); 
webClient.DownloadFileAsync(new Uri(urlDownload),filePath); 
関連する問題