我正在使用ASP.NET核心,并尝试下载一个文件到一个绝对路径。
但我遇到的问题是,文件总是被下载到项目目录中,而文件名本身则得到整个路径的名称。
我的守则:
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中。
反斜杠和冒号被替换为一些特殊字符,因为文件名中不允许反斜杠和冒号。
发布于 2021-02-24 16:35:59
更新
这对我起了作用:
using (WebClient client = new WebClient()) {
client.DownloadFile("https://localhost:5001/", @"D:\file.html");
}根据这一点和其他答案,您的绝对路径应该可以工作。您确定您的路径格式正确且目标文件夹存在吗?
原始答案
如果其他所有操作都失败,请使用此方法,因为保存到有效文件夹应该有效。
WebClient.DownloadFile将下载到当前应用程序(由Application.Startup指定)相对路径的位置。来自文档
参数
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);https://stackoverflow.com/questions/66354435
复制相似问题