Search code examples
c#mimemime-types

Using .NET, how can you find the mime type of a file based on the file signature not the extension


I am looking for a simple way to get a mime type where the file extension is incorrect or not given, something similar to this question only in .Net.


Solution

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