How to get original file name of a file from url - c#

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

Related

Hide Json file containing GOOGLE_APPLICATION_CREDENTIALS when building executable file in Visualstudio [SOLVED]

currently I am developing a tool that interacts with a Firebase Firestore database. When I want to make the C# Forms Application an executable file I get the .exe but also the json file which contains the Google App Credentials. However, I want to forward the tool so that you can't see the json file or read the contents of the file, so you only need the .exe file. Is there a way to achieve this? For example, define the app credentials in a C# script so that it compiles to the .exe file? If so how?
My current implementation looks like this:
string path = AppDomain.CurrentDomain.BaseDirectory + #"cloudfire.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
The cloudfire.json file is directly contained in the namespace "LUX".
I also tried making the cloudfire.json file a resource, since i read this post but then the problem is, that i can't set the path of the .json, if i try it like that:
var assembly = Assembly.GetExecutingAssembly();
string resourceName = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith("cloudfire.json"));
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", resourceName);
I get the error: System.InvalidOperationException: "Sequence contains no matching element"
Is there maybe a way to set the "GOOGLE_APPLICATION_CREDENTIALS" to the embedded cloudfire.json ressource file?
EDIT:
I solved the problem by adding the "cloudfire.json" file to Resources.resx and changed the modifier to public. Like mentioned here.
Since you can only set the GOOGLE_APPLICATION_CREDENTIALS by using this code:
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "path to file");
I solved it by creating a temporary file:
byte[] resourceBytes = Properties.Resources.cloudfire;
// Write the resource to a temporary file
string tempPath = Path.GetTempFileName();
File.WriteAllBytes(tempPath, resourceBytes);
// Set the GOOGLE_APPLICATION_CREDENTIALS environment variable
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", tempPath);
Add you file as embedded resource with name. And try to read by following code:
var resources = new ResourceManager("<namespace>", Assembly.GetExecutingAssembly());
var obj = resources.GetObject(<embedded_resource_key>);
or
var str = resources.GetString(<embedded_resource_key>)

C# WebClient download file to absolute path

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

How to Combine Two paths?

I have an XmlTextReader to read series of XML files to load some information in to my program.
However, in some XML files I have the file name of an image and I want to load that image.
But the problem is the XML file does not have the full path of the image.
<Image id="ImageId" File="Image.bmp" />
<!-- full path is not available. Image is behind XML-->
This means the Image exist where the xml file exists.
for some reason, the only way to get the path of the XML file is to get the path of the XmlTextReader reading the current XML file.
I did some research and I found out you can retrieve the XML path from the XmlTextReader as below:
string path = reader.BaseURI; // this will get the path of reading XML
// reader is XmlTextReader
How can I combine path with the image's path?
I have tried the following way:
string FullImagePath = Path.Combine(reader.BaseURI, imagePath);
These are the values of the variables:
reader.BaseURI is "file:///D:/.../currentXml.xml"
imagePath is "Image.bmp".
Finally, FullImagePath, after assigning the result of Path.Combine is file:///D:/.../currentXml.xml\\Image.bmp, which is not what I expect.
Expected path of the image is: D:/.../Image.bmp, in the same directory as currentXml.xml.
So how can I get the path of the image file?
You have a two different problems that you need to solve separately.
Depending on the API used to consume the image file, a file:// URI path may or may not be supported. So you'd want to make that a local path as explained in Convert file path to a file URI?:
string xmlPath = "file://C:/Temp/Foo.xml";
var xmlUri = new Uri(xmlPath); // Throws if the path is not in a valid format.
string xmlLocalPath = xmlUri.LocalPath; // C:\Temp\Foo.xml
Then you want to build the path to the image file, which resides in the same directory as the XML file.
One way to do that is to get the directory that file is in, see Getting the folder name from a path:
string xmlDirectory = Path.GetDirectoryName(xmlLocalPath); // C:\Temp
Then you can add your image's filename:
string imagePath = Path.Combine(xmlDirectory, "image.png"); // C:\Temp\image.png
Or, in "one" line:
string imagePath = Path.Combine(Path.GetDirectoryName(new Uri(reader.BaseURI).LocalPath),
ImagePath);
Path.Combine(Path.DirectoryName(reader.BaseUri), imagePath)
As you are dealing with resolving URLs I would suggest to use XmlUrlResolver in System.Xml:
string localPath = new XmlUrlResolver().ResolveUri(new Uri(baseUri), imageName).LocalPath;

C# get file name from URL

How can I download file name from URL ?
Like if I have URL like http://localhost/?downloadFile=56 and server will return file example.png. Because when I try to use
WebClient wc = new WebClient();
wc.DownloadFileAsync(url, "{FILE-NAME}");
I having problem to get the file name automatically.
Browsers will use the contents of the filename parameter of the Content-Disposition header as the default filename. If such a header is not available, browsers will typically use a generated filename based on the final component of the URL's path component.
See some additional information here: http://blogs.msdn.com/b/ieinternals/archive/2010/06/07/content-disposition-attachment-and-international-unicode-characters.aspx
I'd think you'd have to download the file and then get the file name from the downloaded file. Not sure how this is a programming question though.

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