C# WebClient 下载文件到绝对路径 更新原答案参数

问题描述

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

但我遇到的问题是文件总是下载到项目目录,文件名本身获取整个路径的名称

我的代码

//package com.company;

使用此代码后,文件将保存在项目文件夹中,文件名为 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 中,文件名为 C:\Users\User

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

解决方法

更新

这对我有用:

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

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

原答案

如果所有其他方法都失败,请使用此选项,因为保存到有效文件夹应该可以。

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

参数

address Uri
指定为字符串的 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);