WebClient如何自动添加文件夹?
How can the WebClient automatically add folders?
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);
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);