在我的控制台应用程序中,我正在从给定的URL下载一个..xlsx文件。如果我将下载路径设置为"C:\Temp\Test.xlsx“,则下载工作正常,并且可以在Excel中打开该文件。但是,如果我将路径设置为"C:\SomeFolder\SomeSubfolder\Test.xlsx“,就会在指定的位置得到一个名为'Test.xlsx‘的文件夹。
下面是我下载文件的代码:
public void DownloadFile(string sourceUrl, string targetPath
{
try
{
CreateDirectoryIfNotExists(targetPath);
using (WebClient webClient = new WebClient())
{
webClient.UseDefaultCredentials = true;
webClient.DownloadFile(sourceUrl, targetPath);
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.Write(e);
Console.ReadLine();
}
}
下面是我创建目录的方法,如果目录还不存在的话:
private void CreateDirectoryIfNotExists(string targetPath)
{
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(targetPath)))
{
System.IO.Directory.CreateDirectory(targetPath);
}
}
将targetPath
设置为“C:\Temp\Test.xlsx”的结果:
将targetPath
设置为“C:\SomeFolder\SomeSubfolder\Test.xlsx”的结果:
是否有理由将我的文件保存为文件夹而不是文件?
任何帮助都是非常感谢的。
发布于 2016-02-12 05:31:05
您正在从目标路径创建目录。更改这一行
System.IO.Directory.CreateDirectory(targetPath);
至
System.IO.Directory.CreateDirectory(new System.IO.FileInfo(targetPath).DirectoryName));
https://stackoverflow.com/questions/35363496
复制