C# WebClient.DownloadFile的无法解释的行为

C# WebClient.DownloadFile的无法解释的行为,c#,file,webclient,C#,File,Webclient,在我的控制台应用程序中,我正在从给定的URL下载一个.xlsx文件。如果我将下载路径设置为“C:\Temp\Test.xlsx”,下载将按预期工作,我可以在Excel中打开该文件。但是如果我将路径设置为“C:\SomeFolder\SomeSubfolder\Test.xlsx”,我会在指定位置得到一个名为“Test.xlsx”的文件夹 以下是我下载文件的代码: public void DownloadFile(string sourceUrl, string targetPath {

在我的控制台应用程序中,我正在从给定的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);


有问题的文件夹到底是什么?如果将文件从
c:\temp
复制到另一个文件夹,会看到什么?粘贴所有代码?您可能在做其他错误的事情,例如在某处调用Directory.CreateDirectory。尝试删除文件夹
Test.xlsx
,然后再次运行程序。如果重新创建目录,这是您的问题
System.IO.Directory.CreateDirectory(new System.IO.FileInfo(targetPath).DirectoryName));