In this article I will explain with an example, how to get MIME type (Content Type) of a File in ASP.Net MVC.
 
 

Files Folder Location

Files are stored in the Folder (Directory) named Files as shown below.
Get MIME Type (Content Type) of a File in ASP.Net MVC
 
 

Namespaces

You need to import the following namespace.
using System.IO;
 
 

Controller

The Controller consists of following Action Methods.

Action method for handling Home GET operation

Inside this Action method, the path of the file is passed as parameter to GetFileName method of Path class which gives the name of the file.
Finally, the file name is passed as parameter to GetMimeMapping method of MimeMapping class which determines the MIME type or the Content Type of the file and the View is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        string word = MimeMapping.GetMimeMapping(Path.GetFileName(Server.MapPath"~/Files/sample.docx")));
        string excel = MimeMapping.GetMimeMapping(Path.GetFileName(Server.MapPath("~/Files/sample.xlsx")));
        string pdf = MimeMapping.GetMimeMapping(Path.GetFileName(Server.MapPath("~/Files/sample.pdf")));
        string image = MimeMapping.GetMimeMapping(Path.GetFileName(Server.MapPath("~/Files/sample.png")));
        return View();
    }
}
 
 
View
The View is kept empty as it is not required.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
    </div>
</body>
</html>
 
 

Screenshot

Get MIME Type (Content Type) of a File in ASP.Net MVC
 
 

Downloads