Using .NET, how can you find the mime type of a file based on the file signature not the extension
In Urlmon.dll, there's a function called FindMimeFromData
.
From the documentation
MIME type detection, or "data sniffing," refers to the process of determining an appropriate MIME type from binary data. The final result depends on a combination of server-supplied MIME type headers, file extension, and/or the data itself. Usually, only the first 256 bytes of data are significant.
So, read the first (up to) 256 bytes from the file and pass it to FindMimeFromData
.
File Mime Type Checking
I ended up mixing some solutions from here, because I am not using the HttpFileBase and only have the file stream, I had to read the first few bytes of the stream to determine the mime type.
Note: I don't use the registry technique because I don't know what will or wont be installed on the servers.
Check file format signature with .net core 2.1 api
I didn't find any 'lib/nuget/class' specific for .net core that might make our life easier. So, I returned to a common approach which is comparing byte file header with examples.
private readonly Dictionary<string, byte[]> _mimeTypes = new Dictionary<string, byte[]>
{
{"image/jpeg", new byte[] {255, 216, 255}},
{"image/jpg", new byte[] {255, 216, 255}},
{"image/pjpeg", new byte[] {255, 216, 255}},
{"image/apng", new byte[] {137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82}},
{"image/png", new byte[] {137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82}},
{"image/bmp", new byte[] {66, 77}},
{"image/gif", new byte[] {71, 73, 70, 56}},
};
private bool ValidateMimeType(byte[] file, string contentType)
{
var imageType = _mimeTypes.SingleOrDefault(x => x.Key.Equals(contentType));
return file.Take(imageType.Value.Length).SequenceEqual(imageType.Value);
}
How to reliably detect mime type of uploaded [text-based] file in asp.net?
This is a duplicate of the Using .NET, how can you find the mime type of a file based on the file signature not the extension question here on stackoverflow. This one includes an answer with a code sample to use the FindMimeFromData method from urlmon.dll.
Related Topics
Is Is Possible to Export Functions from a C# Dll Like in VS C++
Captured Variable in a Loop in C#
How to Enable Assembly Bind Failure Logging (Fusion) in .Net
The Entity Cannot Be Constructed in a Linq to Entities Query
How to Turn a C# Object into a Json String in .Net
Why Is Floating Point Arithmetic in C# Imprecise
Public Fields Versus Automatic Properties
Reflection - Get Attribute Name and Value on Property
Convert Utc/Gmt Time to Local Time
Why Is Jsonrequestbehavior Needed
What Does the Unary Plus Operator Do
Implementing Inotifypropertychanged - Does a Better Way Exist
An Async/Await Example That Causes a Deadlock
Is Using Random and Orderby a Good Shuffle Algorithm
How to Find Out Which Process Is Locking a File Using .Net
Quickest Way to Convert a Base 10 Number to Any Base in .Net