-3

is there any method to get (actually guess!) the extension file? in my program, somewhere I get a file which the application analyze it for understanding is it ZIP or MOV.

I found out this, but it does not support MOV and ZIP.

Update:

By creating a text file which contains the first 8 bits of the file signatures. and the below code, I can determine every file which has no extension. this page could be a good reference.

        string rootPath = $"{name}";
        using (FileStream fsSource = new FileStream(rootPath, FileMode.Open, FileAccess.Read))
        {
            byte[] fileBytes = new byte[8]; // the number of bytes you want to read
            fsSource.Read(fileBytes, 0, 8);

            /*
             zip = 50-4B-03-04-0A-00-00-00
             mov = 00-00-00-20-66-74-79-70
             html = 3C-21-64-6F-63-74-79-70
             rar 1 = 52-61-72-21-1A-07
             rar 5 = 52-61-72-21-1A-07 

            */
            string filestring = BitConverter.ToString(fileBytes);
            // string filestring = Encoding.UTF8.GetString(fileBytes); 
            File.WriteAllText($"{DownloadPath}\\filestring.txt", filestring);
        }
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
joei
  • 333
  • 2
  • 11

1 Answers1

5

Just read the header section of the file (several bytes at the beginning of the file) and you can detect its format.

For example this page has information about mov files.

You can read file header like this code (here I have assumed that reading 4 bytes will be enough, however, you can change it as you like if you need more/less bytes to determine the format):

 using (FileStream fsSource = new FileStream(pathSource, FileMode.Open, FileAccess.Read))
 {
     byte[] bytes = new byte[4]; // the number of bytes you want to read
     fsSource.Read(bytes, 0, 4);
 }
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171