Home > Software engineering >  How to get original file name of a file from url
How to get original file name of a file from url

Time:07-30

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?

CodePudding user response:

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 to get only the version respource of a file.

CodePudding user response:

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