WebClient.DownloadFile的令人费解的行为
问题描述:
在我的控制台应用程序中,我正在从给定的URL下载.xlsx文件。如果我将下载路径设置为“C:\ Temp \ Test.xlsx”,则下载按预期工作,我可以在Excel中打开该文件。但是,如果我将路径设置为“C:\ SomeFolder \ SomeSubfolder \ Test.xlsx”,我会在指定位置得到名称为“Test.xlsx”的文件夹。WebClient.DownloadFile的令人费解的行为
这里就是我下载的文件中的代码:
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));
+0
您是对的。我应该看到这一点。 –
什么* *究竟是有问题的文件夹?如果将文件从'c:\ temp'复制到另一个文件夹,您看到了什么? –
粘贴你的所有代码?您可能正在做其他事情,例如在某处调用Directory.CreateDirectory。 尝试删除“Test.xlsx”文件夹并再次运行您的程序。如果重新创建目录是您的问题 – wal