c# - WebClient如何自动添加文件夹?

标签 c# webclient

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

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

如何自动添加文件夹?

最佳答案

您需要首先检查所需的文件夹是否不存在,然后创建它,然后开始下载文件:

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/

相关文章:

c# - 如何在 WebClient 中设置 User-Agent

.net - 从 Internet 下载 URL 中包含特定日期时间的图像

c# - 从 MVC3 Action 中获取值(value)

c# - 为什么 Guid.ToString ("n") 与从同一 guid 的字节数组生成的十六进制字符串不同?

c# - 如何处理意外的日期和时间格式?

c# - 如何避免重复的接口(interface)代码?

c# - .Net DownloadFileTaskAsync 健壮的 WPF 代码

c# - 在 C# 中使用 System.ComponentModel.BackgroundWorker 和 lambda 的最佳方式

javascript - ASP.NET 如何将 javascript 添加到动态 gridview 文本框 (ItemTemplate)

c# - 下载网站的所有图像