Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As mentioned, MIME magic is the only way to do this. Many platforms provide up-to-date and robust MIME magic files and code to do this efficiently. The only way to do this in .NET without any 3rd party code is to use <code>FindMimeFromData</code> from urlmon.dll. Here's how:</p> <pre><code>public static int MimeSampleSize = 256; public static string DefaultMimeType = "application/octet-stream"; [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)] private extern static uint FindMimeFromData( uint pBC, [MarshalAs(UnmanagedType.LPStr)] string pwzUrl, [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer, uint cbSize, [MarshalAs(UnmanagedType.LPStr)] string pwzMimeProposed, uint dwMimeFlags, out uint ppwzMimeOut, uint dwReserverd ); public static string GetMimeFromBytes(byte[] data) { try { uint mimeType; FindMimeFromData(0, null, data, (uint)MimeSampleSize, null, 0, out mimeType, 0); var mimePointer = new IntPtr(mimeType); var mime = Marshal.PtrToStringUni(mimePointer); Marshal.FreeCoTaskMem(mimePointer); return mime ?? DefaultMimeType; } catch { return DefaultMimeType; } } </code></pre> <p>This uses the Internet Explorer MIME detector. This is the same code used by IE to send a MIME type along with uploaded files. You can see the <a href="http://msdn.microsoft.com/en-us/library/ms775147%28v=vs.85%29.aspx" rel="noreferrer">list of MIME types supported by urlmon.dll</a>. One thing to watch out for is <code>image/pjpeg</code> and <code>image/x-png</code> which are non-standard. In my code I replace these with <code>image/jpeg</code> and <code>image/png</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload