在我的控制台应用程序中,我从给定的 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”的结果:
为什么我的文件被保存为文件夹而不是文件?
感谢任何帮助。
最佳答案
您正在从目标路径创建目录。改变这一行
System.IO.Directory.CreateDirectory(targetPath);
到
System.IO.Directory.CreateDirectory(new System.IO.FileInfo(targetPath).DirectoryName));
关于c# - WebClient.DownloadFile 的莫名其妙的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35363496/