WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(urlDownload), @"C:FilesTestFoldertest.txt");
如果我想将 test.txt 文件保存到文件夹中,则WebClient
仅在我之前创建这些文件夹(FilesTestFolder)
时保存文件。但是,例如,我没有创建文件夹Test
,Webclient
什么也没保存。
如何自动添加文件夹?
您需要首先检查所需的文件夹是否尚不存在,然后创建它,然后开始下载文件:
string path = "@C:FilesTestFolder";
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:FilesTestFolder";
string filePath = path +"\test.txt";
CreateFolder(path);
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(urlDownload),filePath);