Using .Net, How to Find the Mime Type of a File Based on the File Signature Not the Extension

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



Leave a reply



Submit