Find File Type From Magic Number Of File In MVC 5

Introduction

 
In this article, we are going to upload a document from HTML input & we can find the magic number of that file & from that number we can find the type of that file.
 
Magic Number:
  • A magic number is a number embedded at or near the beginning of a file that indicates its file format (i.e. the type of file it is).
  • This number is not visible to us. 
  • Every file has a number that represents the name of file types which is hexadecimal format.
  • In our program, we will convert it into bytes and an array for checking file type.
Chart for the magic number
 
table
 
Note: Refer chart source for file types Wikipedia.
 
Step 1: Create a simple project in Visual Studio 2013.
 
Empty template
 
Step 2: Create one controller (right-click on the controller folder, add, then controller).
 
Controller
 
Step 3: Now from Index action create single view (right-click on action method => add view) for this action.
 
Add view
 
Step 4: Now add code for UI which will represent one input file button, one submit button & some label (to show error, success, file name, etc).
  1. <h2>Find File Type From Magic Number of File</h2>    
  2. @using (Html.BeginForm("Index",    
  3. "File_Upload",    
  4. FormMethod.Post,    
  5. new { enctype = "multipart/form-data" }))    
  6. {    
  7.    <label for="file">Upload file :</label>    
  8.    <input type="file" name="file" id="file" /><br>    
  9.    <input type="submit" id="submit" /> <br />    
  10.    <p>Program_Errors will show here:</p>    
  11.    @ViewBag.error    
  12.    <p>You have uploaded file type is : @ViewBag.File_Type </p>    
  13.    <br />    
  14.    @ViewBag.Message    
  15.    <br />    
  16.    @ViewBag.signature    
  17.    <br />    
  18.    @ViewBag.out_put    
  19. }   
    Step 5: Now create another action method with the same name as the index & pass the ttpPostedFileBase object.
     
    In our action we will do the following things:
    • Will create one array in which we can store the above magic number so that it will help us at the end to compare file type in the switch case.
    • We need to add namespace using System.IO;
    • Create one folder in our solution file as “Docs” to upload a document in this folder (download code for more information). 
    • Substring to select the first 11 characters from hexadecimal array because every file has a different magic number so I chose only three which have the same characters.
      1. [HttpPost]  
      2.   
      3. public ActionResult Index(HttpPostedFileBase file)  
      4. {  
      5.     string ext = null;  
      6.     string[] file_hexa_signature = {  
      7.         "38-42-50-53",  
      8.         "25-50-44-46",  
      9.         "4D-4D-00-2A",  
      10.         "4D-4D-00-2A"  
      11.     };  
      12.   
      13.     try  
      14.     {  
      15.         ext = System.IO.Path.GetExtension(file.FileName).ToLower();  
      16.     }  
      17.     catch (Exception ex)  
      18.     {  
      19.         ViewBag.error = ex.Message;  
      20.     }  
      21.   
      22.     if (ext == null)  
      23.     {  
      24.         ViewBag.error = "please select onlt psd, pdf, tif file types only";  
      25.     }  
      26.   
      27.     if (file != null && file.ContentLength > 0)  
      28.     {  
      29.         string str = Path.GetFileName(file.FileName);  
      30.         string path = Path.Combine(Server.MapPath("~/Docs"),  
      31.             Path.GetFileName(file.FileName));  
      32.         file.SaveAs(path);  
      33.         BinaryReader reader = new BinaryReader(new FileStream(Convert.ToString(path), FileMode.Open, FileAccess.Read, FileShare.None));  
      34.         reader.BaseStream.Position = 0x0; // The offset you are reading the data from    
      35.         byte[] data = reader.ReadBytes(0x10); // Read 16 bytes into an array    
      36.         string data_as_hex = BitConverter.ToString(data);  
      37.         reader.Close();  
      38.   
      39.         // substring to select first 11 characters from hexadecimal array    
      40.         string my = data_as_hex.Substring(0, 11);  
      41.         string output = null;  
      42.         switch (my)  
      43.         {  
      44.             case "38-42-50-53":  
      45.                 output = " => psd";  
      46.                 break;  
      47.   
      48.             case "25-50-44-46":  
      49.                 output = " => pdf";  
      50.                 break;  
      51.   
      52.             case "49-49-2A-00":  
      53.                 output = " => tif";  
      54.                 break;  
      55.   
      56.             case "4D-4D-00-2A":  
      57.                 output = " => tif";  
      58.                 break;  
      59.   
      60.             case "null":  
      61.                 output = "file type is not matches with array";  
      62.                 break;  
      63.   
      64.         }  
      65.   
      66.         ViewBag.Message = data_as_hex;  
      67.         ViewBag.signature = my;  
      68.         ViewBag.out_put = output;  
      69.     }  
      70.     return View();  

    Step 6: Now run our program.
     
    run our program
     
    Step 7: Now click on the browse button & select the file as shown.
     
    click on browse button
     
    Step 8: After selecting the file it will show the file name.
     
    shows file name
     
    Step 9: Now click on submit query & our output will be like. the following
     
    click on submit query
     

    Summary

     
    This article will help freshers as well as experienced candidates.
     
    Hope you enjoyed this complete article. Don’t forget to comment.