2023
Get Mime Type for any extension in Asp.Net
82
To find the MIME type of a file based on its extension in C# Asp.Net project, you can use the MimeTypeMap class from the Microsoft.AspNetCore.StaticFiles namespace. This class provides a mapping between file extensions and corresponding MIME types. Here's an example:
using Microsoft.AspNetCore.StaticFiles; class Program { static void Main() { string extension = ".jpg"; // Replace with the file extension you want to find the MIME type for var provider = new FileExtensionContentTypeProvider(); if (provider.TryGetContentType(extension, out string mimeType)) { //Printing Mime type Console.WriteLine($"MIME Type for {extension}: {mimeType}"); } else { Console.WriteLine($"No MIME Type found for {extension}"); } } }
In this example, the FileExtensionContentTypeProvider class is getting used to map file extensions to MIME types.It returns a boolean value indicating whether the MIME type was found. If the MIME type is found, it is stored in the mimeType variable and than display in console. If no MIME type is found, a corresponding message is printed. You can make the change according to your requirements.
Note that you need to have the Microsoft.AspNetCore.StaticFiles NuGet package installed in your project to use the FileExtensionContentTypeProvider class.
So this is how you can get mime type of any extension in asp.net.