【问题标题】:C# WebClient download file to absolute pathC# WebClient 下载文件到绝对路径
【发布时间】:2021-02-24 16:00:30
【问题描述】:

我正在使用 ASP.NET Core 并尝试将文件下载到绝对路径。

但我遇到的问题是文件总是被下载到项目目录中,而文件名本身就是整个路径的名称。

我的代码:

string path = @"C:\Users\User\file.txt";
string url = "https://example.com/file.txt";
using (var client = new WebClient())
{
    client.DownloadFile(url, path);
}

使用此代码后,文件会以文件名C:\Users\User\file.txt 保存在项目文件夹中,而不是以文件名file.txt 保存在目录C:\Users\User 中。

反斜杠和冒号被一些特殊字符替换,因为它们不允许出现在文件名中。

【问题讨论】:

    标签: c# webclient


    【解决方案1】:

    更新

    这对我有用:

    using (WebClient client = new WebClient()) {
        client.DownloadFile("https://localhost:5001/", @"D:\file.html");
    }
    

    根据这个和other answers,您的绝对路径应该可以工作。您确定您的路径格式正确且目标文件夹存在吗?

    原答案

    如果一切都失败了就使用这个,因为保存到一个有效的文件夹应该可以。

    WebClient.DownloadFile 将下载到当前应用程序的位置(由Application.Startup 指定)获取相对路径。来自docs

    参数

    address Uri
    指定为 String 的 URI,从中下载数据。

    fileName String
    接收数据的本地文件名。

    如果你要使用WebClient,你需要在下载后移动文件,例如

    // Download to a local file.
    using (var client = new WebClient())
    {
        client.DownloadFile(url, fileName);
    }
    
    // Get the full path of the download and the destination folder.
    string fromPath = Path.Combine(Application.StartupPath, fileName);
    string toPath = Path.Combine(destinationFolder, fileName);
    
    // Move the file.
    File.Move(fromPath, toPath);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 2020-08-18
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多