问题
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