繁体   English   中英

C# WebClient下载文件到绝对路径

[英]C# WebClient download file to absolute path

我正在使用 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 ,而不是保存在目录C:\Users\User中,文件名为file.txt

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

更新

这对我有用:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM