C# WebClient download file to absolute path - c#

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.

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

Related

How to get original file name of a file from url

I have uploaded my file to my website with a random name. Now I want to get the original file name.
I have tried to get the file name:
var dllUrl = "https://cdn.example.com/c6244c971f.dll";
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(dllUrl);
Console.WriteLine(myFileVersionInfo.OriginalFilename);
but it did not work.
How can I get the original name from the version resource?
The parameter of FileVersionInfo.GetVersionInfo is a file name, not a URL.
You need to download the file (see e.g. here) to a temporary file and then use FileVersionInfo.GetVersionInfo(temporaryFile).
There is no other was to do this, because the original file name is not encoded in the URL nor is there a HTTP verb (or any other standardized way) to get only the version resource of a file.
I agree with Klaus Gütter. You need to download the file.
Here is the code:
var uri = "https://cdn.example.com/c6244c971f.dll";
var uniqueFileName = Path.GetRandomFileName();
var uniqueFilePath = Path.Combine(#"D:\temp", uniqueFileName);
// Download the file
new WebClient().DownloadFile(uri, uniqueFilePath);
// Get file version info
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(uniqueFilePath);
Console.WriteLine(myFileVersionInfo.OriginalFilename);
// Delete the file from local disk
File.Delete(uniqueFilePath);

Convert Relative Path to Absolute Path

I am trying to open a Help.txt file in windows Forms using a linkLabel. However unable to convert from absolute to relative path.
First, I try to get the absolute path of the exe file. Which is successful.
Second, get only directory of the exe file. Which is successful.
Third, I am trying to combine the directory with the relative path of the Help.txt file. Which is unsuccessful.
Exe file lives in -> \Project\bin\Debug folder, However the Help.txt file lives in \Project\Help folder. This is my code:-
string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
string Dir = Uri.UnescapeDataString(Path.GetDirectoryName(exeFile));
string path = Path.Combine(Dir, #"..\..\Help\Help.txt");
System.Diagnostics.Process.Start(path);
The result of my path is -> \Project\bin\Debug....\Help\Help.txt
You need to use Path.GetFullPath() to have the upper directory "../../" taken into account, see below :
string exeFile = new System.Uri(Assembly.GetEntryAssembly().CodeBase).AbsolutePath;
string Dir = Path.GetDirectoryName(exeFile);
string path = Path.GetFullPath(Path.Combine(Dir, #"..\..\Help\Help.txt"));
System.Diagnostics.Process.Start(path);
Per the MSDN of GetFullPath : Returns the absolute path for the specified path string.
Whereas Path.Combine Combines strings into a path.

Download files and create the same folder structure as the Host

I have a config file which consists of list of URIs I want to download. For example,
http://xyz.abc.com/Dir1/Dir3/sds.txt
http://xyz.abc.com/Dir2/Dir4/jhjs.txt
http://xyz.abc.com/Dir1/itr.txt
I want to read the config file and and copy each URL but at the same time create the same directory structure as on the host. For example, for the first line in the config file, I want to create the directory structure Dir1/Dir3 on my local machine (if it doesn't exist) and then copy sds.exe to .../Dir1/Dir3/
How do I do this in C#?
What I have till now is:
string myStringWebResource; //Read this from the config file
System.IO.StreamReader file =
new System.IO.StreamReader("config.txt");
// Read the config file line by line
while ((myStringWebResource = file.ReadLine()) != null)
{
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
//How do I keep the original filename, e.g. sds.txt
string outputFilename = #"" + ???";
Console.WriteLine("Downloading ...");
// Download the Web resource and save it into
// the current filesystem folder.
try
{
myWebClient.DownloadFile(myStringWebResource, outputFilename);
Console.WriteLine("Successful");
}
catch (WebException e)
{
Console.WriteLine("Fail" + e.Message);
}
}
}
While this lets me download all the files in the config file,
I have this problem of having to name them after download, how can I retain their original name?
All the files get downloaded in the same folder. How could I replicate the folder structure from the Host?
My suggestion would we to filter the host out. Then split each remaining string on the /. Then build a method that takes a string[] as argument to create the directory structure. Move the file with filename (last item in the array) in that directory, using the original path (without host).
If the host is variable, remove everything before the third /.

how to get the proper path using fileupload in asp. net?

I'm having problem on getting the file path using file upload. When I tested to upload a file on the file upload, I've noticed that my file upload is getting the wrong path. The right path is C:\RightPath\B1.txt but the I check it its getting the wrong path which is 'C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\B1.txt'..
here's my code behind...
string OasisPath = Path.GetFullPath(cmdUpload.FileName);
StreamReader OasisFile = new StreamReader(OasisPath);
string B1String = OasisFile.ReadLine();
OasisFile.Close();
I also tried this one..
string OasisPath = Server.MapPath(cmdUpload.FileName);
StreamReader OasisFile = new StreamReader(Server.MapPath(cmdUpload.FileName)); // I get this error Could not find file 'C:\Rightpath\B1.txt'
string B1String = OasisFile.ReadLine();
OasisFile.Close();
Please advice me...
thanks,,
You need to explicitly set the path of the file when you save it. The server doesn't know what path the file was stored in on the client machine. If you don't specify a path it will just save it in the current environment's default path.

path to subfolder for a text file

StreamReader content1 = File.OpenText("../DATA/heading.txt");
I have a txt file in a subfolder called DATA, I am trying to access this file from code but the code goes to the .net runtime directitory and not the application directory, thanks for the help
string filePath = Server.MapPath("/Data/heading.txt");
StreamReader content1 = File.OpenText(filePath);
Try using the Application's Entry assembly to get your text file path like this.
Assembly asm = Assembly.GetEntryAssembly();
string appDir = Path.GetDirectoryName(asm.Location);
string filePath = Path.Combine(appDir, "../DATA/heading.txt");
StreamReader content1 = File.OpenText(filePath);
This will work for any application that starts as an exe.
Since you marked this as asp.net are you looking on the server from asp.net? If so try Server.MapPath http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
From MSDN - http://msdn.microsoft.com/en-us/library/system.io.file.opentext.aspx
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
http://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory.aspx
So your current directory is not set to your application directory.

Categories

Resources