WebClient如何自动添加文件夹?

时间:2017-03-22 12:16:14

标签: c# webclient

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

如果我想将test.txt文件保存到该文件夹​​,WebClient仅在我之前创建这些文件夹(Files\Test\Folder)时保存文件。 但是,例如我没有创建文件夹TestWebclient不会保存任何内容。

如何自动添加文件夹?

1 个答案:

答案 0 :(得分: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);