WebClient 如何自动添加文件夹? [英] How can the WebClient automatically add folders?
本文介绍了WebClient 如何自动添加文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(urlDownload), @"C:\Files\Test\Folder\test.txt");
如果我想将 test.txt 文件保存到文件夹中,WebClient
只会在我创建这些文件夹时保存文件 (Files\Test\Folder)
之前.但是,例如,我没有创建文件夹 Test
,Webclient
不保存任何内容.
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.
如何自动添加文件夹?
推荐答案
您需要先检查所需文件夹是否已经存在,然后创建它,然后开始下载文件:
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);
}
}
并调用它:
string path = "@C:\Files\Test\Folder";
string filePath = path +"\\test.txt";
CreateFolder(path);
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(urlDownload),filePath);
这篇关于WebClient 如何自动添加文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文