简体   繁体   English

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

[英]C# WebClient download file to absolute path

I'm working with ASP.NET Core and try to download a file to an absolute path.我正在使用 ASP.NET 内核并尝试将文件下载到绝对路径。

But the problem I have is that the file always gets downloaded to the project directory and the filename itself gets the name of the whole path.但我遇到的问题是文件总是被下载到项目目录中,而文件名本身就是整个路径的名称。

My Code:我的代码:

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

With this code the file gets then saved in the project folder with the file name C:\Users\User\file.txt , instead of being saved in the directory C:\Users\User with the file name file.txt .使用此代码,文件将保存在项目文件夹中,文件名为C:\Users\User\file.txt ,而不是保存在目录C:\Users\User中,文件名为file.txt

The backslashes and the colon get replaced with some special characters, because they are not allowed in the filename.反斜杠和冒号被一些特殊字符替换,因为它们在文件名中是不允许的。

Update更新

This worked for me:这对我有用:

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

According to this and other answers , your absolute path should work.根据这个和其他答案,你的绝对路径应该有效。 Are you certain your path is formatted correctly and the destination folder exists?您确定您的路径格式正确并且目标文件夹存在吗?

Original Answer原始答案

Use this if all else fails, since saving to a valid folder should work.如果一切都失败了,请使用它,因为保存到有效的文件夹应该可以工作。

WebClient.DownloadFile will download to the location of the current application (specified by Application.Startup ) for a relative path. WebClient.DownloadFile将下载到当前应用程序的位置(由Application.Startup指定)获取相对路径。 From the docs :文档

Parameters参数

address Uri
The URI specified as a String, from which to download data.指定为字符串的 URI,从中下载数据。

fileName String
The name of the local file that is to receive the data.要接收数据的本地文件的名称。

If you are going to use WebClient , you will need to move the file after you have downloaded it, eg如果您要使用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