Skip to main content
 首页 » 编程设计

c#之WebClient.DownloadFile 的莫名其妙的行为

2024年05月06日47tintown

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