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 in hexadecimal format.
  • In our program, we will convert it into bytes and an array for checking file type.

Chart for the magic number

Magic table

Note. Refer to 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 the Index action create a single view (right-click on action method => add view) for this action.

Index action

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

<h2>Find File Type From Magic Number of File</h2>
@using (Html.BeginForm("Index", "File_Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <label for="file">Upload file :</label>
    <input type="file" name="file" id="file" /><br>
    <input type="submit" id="submit" /><br />
    <p>Program_Errors will show here:</p>
    @ViewBag.error
    <p>You have uploaded file type is: @ViewBag.File_Type </p>
    <br />
    @ViewBag.Message
    <br />
    @ViewBag.signature
    <br />
    @ViewBag.out_put
}

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 a 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 the hexadecimal array because every file has a different magic number so I chose only three which have the same characters.
[HttpPost]   

public ActionResult Index(HttpPostedFileBase file)   
{   
    string ext = null;   
    string[] file_hexa_signature = {   
        "38-42-50-53",   
        "25-50-44-46",   
        "4D-4D-00-2A",   
        "4D-4D-00-2A"   
    };   
   
    try   
    {   
        ext = System.IO.Path.GetExtension(file.FileName).ToLower();   
    }   
    catch (Exception ex)   
    {   
        ViewBag.error = ex.Message;   
    }   
   
    if (ext == null)   
    {   
        ViewBag.error = "please select onlt psd, pdf, tif file types only";   
    }   
   
    if (file != null && file.ContentLength > 0)   
    {   
        string str = Path.GetFileName(file.FileName);   
        string path = Path.Combine(Server.MapPath("~/Docs"),   
            Path.GetFileName(file.FileName));   
        file.SaveAs(path);   
        BinaryReader reader = new BinaryReader(new FileStream(Convert.ToString(path), FileMode.Open, FileAccess.Read, FileShare.None));   
        reader.BaseStream.Position = 0x0; // The offset you are reading the data from   
        byte[] data = reader.ReadBytes(0x10); // Read 16 bytes into an array   
        string data_as_hex = BitConverter.ToString(data);   
        reader.Close();   
   
        // substring to select first 11 characters from hexadecimal array   
        string my = data_as_hex.Substring(0, 11);   
        string output = null;   
        switch (my)   
        {   
            case "38-42-50-53":   
                output = " => psd";   
                break;   
   
            case "25-50-44-46":   
                output = " => pdf";   
                break;   
   
            case "49-49-2A-00":   
                output = " => tif";   
                break;   
   
            case "4D-4D-00-2A":   
                output = " => tif";   
                break;   
   
            case "null":   
                output = "file type is not matches with array";   
                break;   
   
        }   
   
        ViewBag.Message = data_as_hex;   
        ViewBag.signature = my;   
        ViewBag.out_put = output;   
    }   
    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.

Submit query

Summary

This article will help freshers as well as experienced candidates.

Hope you enjoyed this complete article. Don’t forget to comment.


Similar Articles