How can the WebClient automatically add folders?

蓝咒 提交于 2019-12-12 02:32:21

问题


WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(urlDownload), @"C:\Files\Test\Folder\test.txt");

If I want to save the test.txt file to the folder, the WebClient saves the file only, when I have created these folders (Files\Test\Folder) before. I have however for example the folder Test not created, the Webclient saves nothing.

How do I do that folders are added automatically?


回答1:


You would need to check first if the required folder does not exists already, then create it and after that start downloading of the file:

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);

more better is to create a method:

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

and call it :

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


来源:https://stackoverflow.com/questions/42951397/how-can-the-webclient-automatically-add-folders

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!