Reputation: 76
I'm working with ASP.NET Core and try to download a file to an absolute path.
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
.
The backslashes and the colon get replaced with some special characters, because they are not allowed in the filename.
Upvotes: 4
Views: 8042
Reputation: 7176
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?
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. From the docs:
Parameters
address Uri
The URI specified as a String, from which to download data.
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, e.g.
// 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);
Upvotes: 3