WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(urlDownload), @"C:\Files\Test\Folder\test.txt");
如果我想将 test.txt 文件保存到该文件夹,WebClient
仅在我创建这些文件夹时保存该文件(Files\Test\Folder)
之前。
然而,例如,我没有创建文件夹 Test
,Webclient
没有保存任何内容。
如何自动添加文件夹?
最佳答案
您需要首先检查所需的文件夹是否不存在,然后创建它,然后开始下载文件:
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);
关于c# - WebClient如何自动添加文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42951397/