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

标签 c# file webclient

在我的控制台应用程序中,我从给定的 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”的结果:

enter image description here

targetPath 设置为“C:\SomeFolder\SomeSubfolder\Test.xlsx”的结果:

enter image description here

为什么我的文件被保存为文件夹而不是文件?

感谢任何帮助。

最佳答案

您正在从目标路径创建目录。改变这一行

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/

相关文章:

Android - 如何打开 res 文件夹中的不同文件?

ruby - 在 Ruby 中读取文件时转到下一行

python - 如何将带有列表键的 python 字典保存到文件中?

c# - 发布数据后如何读取 WebClient 响应?

c# - 如何使用 LINQ 从树中的所有节点获取列表?

c# - 如何实现不带参数的ICommand

c# - 字段的详细 XML 文档。有可能吗?

c# - 方法 'Open' 没有重载需要 1 个或多个参数

c# - 在 HttpClient 和 WebClient 之间做出决定

C# Silverlight WebClient 获取响应的内容类型?