<p>I am looking for a simple way to get a mime type where the file extension is incorrect or not given, something similar to <a href="https://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java">this question</a> only in .Net.</p>

[{'answer_id': 58570, 'author': 'Steve Morgan', 'author_id': 5806, 'author_profile': 'https://Stackoverflow.com/users/5806', 'pm_score': 7, 'selected': True, 'text': '<p>In Urlmon.dll, there\'s a function called <code>FindMimeFromData</code>.</p>\n\n<p>From the documentation </p>\n\n<blockquote>\n  <p>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. </p>\n</blockquote>\n\n<p>So, read the first (up to) 256 bytes from the file and pass it to <code>FindMimeFromData</code>.</p>\n'}, {'answer_id': 62007, 'author': 'Richard Gourlay', 'author_id': 2674, 'author_profile': 'https://Stackoverflow.com/users/2674', 'pm_score': 8, 'selected': False, 'text': '<p>I did use urlmon.dll in the end. I thought there would be an easier way but this works. I include the code to help anyone else and allow me to find it again if I need it.</p>\n\n<pre><code>using System.Runtime.InteropServices;\n</code></pre>\n\n<p>...</p>\n\n<pre><code>    [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]\n    private extern static System.UInt32 FindMimeFromData(\n        System.UInt32 pBC,\n        [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,\n        [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,\n        System.UInt32 cbSize,\n        [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,\n        System.UInt32 dwMimeFlags,\n        out System.UInt32 ppwzMimeOut,\n        System.UInt32 dwReserverd\n    );\n\n    public static string getMimeFromFile(string filename)\n    {\n        if (!File.Exists(filename))\n            throw new FileNotFoundException(filename + " not found");\n\n        byte[] buffer = new byte[256];\n        using (FileStream fs = new FileStream(filename, FileMode.Open))\n        {\n            if (fs.Length &gt;= 256)\n                fs.Read(buffer, 0, 256);\n            else\n                fs.Read(buffer, 0, (int)fs.Length);\n        }\n        try\n        {\n            System.UInt32 mimetype;\n            FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);\n            System.IntPtr mimeTypePtr = new IntPtr(mimetype);\n            string mime = Marshal.PtrToStringUni(mimeTypePtr);\n            Marshal.FreeCoTaskMem(mimeTypePtr);\n            return mime;\n        }\n        catch (Exception e)\n        {\n            return "unknown/unknown";\n        }\n    }\n</code></pre>\n'}, {'answer_id': 1685614, 'author': 'Serguei', 'author_id': 47693, 'author_profile': 'https://Stackoverflow.com/users/47693', 'pm_score': 5, 'selected': False, 'text': '<p>You can also look in the registry.</p>\n\n<pre><code>    using System.IO;\n    using Microsoft.Win32;\n\n    string GetMimeType(FileInfo fileInfo)\n    {\n        string mimeType = "application/unknown";\n\n        RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(\n            fileInfo.Extension.ToLower()\n            );\n\n        if(regKey != null)\n        {\n            object contentType = regKey.GetValue("Content Type");\n\n            if(contentType != null)\n                mimeType = contentType.ToString();\n        }\n\n        return mimeType;\n    }\n</code></pre>\n\n<p>One way or another you\'re going to have to tap into a database of MIMEs - whether they\'re mapped from extensions or magic numbers is somewhat trivial - windows registry is one such place.\nFor a platform independent solution though one would have to ship this DB with the code (or as a standalone library).</p>\n'}, {'answer_id': 1718862, 'author': 'Jamey', 'author_id': 209145, 'author_profile': 'https://Stackoverflow.com/users/209145', 'pm_score': 2, 'selected': False, 'text': '<p>I think the right answer is a combination of Steve Morgan\'s and Serguei\'s answers.  That\'s how Internet Explorer does it.  The pinvoke call to <code>FindMimeFromData</code> works for only 26 hard-coded mime types.  Also, it will give ambigous mime types (such as <code>text/plain</code> or <code>application/octet-stream</code>) even though there may exist a more specific, more appropriate mime type.  If it fails to give a good mime type, you can go to the registry for a more specific mime type.  The server registry could have more up-to-date mime types.</p>\n\n<p>Refer to:  <a href="http://msdn.microsoft.com/en-us/library/ms775147(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms775147(VS.85).aspx</a></p>\n'}, {'answer_id': 7161265, 'author': 'Anykey', 'author_id': 907728, 'author_profile': 'https://Stackoverflow.com/users/907728', 'pm_score': 7, 'selected': False, 'text': '<p>I\'ve found a hard-coded solution, I hope i will help somebody:</p>\n\n<pre><code>public static class MIMEAssistant\n{\n  private static readonly Dictionary&lt;string, string&gt; MIMETypesDictionary = new Dictionary&lt;string, string&gt;\n  {\n    {"ai", "application/postscript"},\n    {"aif", "audio/x-aiff"},\n    {"aifc", "audio/x-aiff"},\n    {"aiff", "audio/x-aiff"},\n    {"asc", "text/plain"},\n    {"atom", "application/atom+xml"},\n    {"au", "audio/basic"},\n    {"avi", "video/x-msvideo"},\n    {"bcpio", "application/x-bcpio"},\n    {"bin", "application/octet-stream"},\n    {"bmp", "image/bmp"},\n    {"cdf", "application/x-netcdf"},\n    {"cgm", "image/cgm"},\n    {"class", "application/octet-stream"},\n    {"cpio", "application/x-cpio"},\n    {"cpt", "application/mac-compactpro"},\n    {"csh", "application/x-csh"},\n    {"css", "text/css"},\n    {"dcr", "application/x-director"},\n    {"dif", "video/x-dv"},\n    {"dir", "application/x-director"},\n    {"djv", "image/vnd.djvu"},\n    {"djvu", "image/vnd.djvu"},\n    {"dll", "application/octet-stream"},\n    {"dmg", "application/octet-stream"},\n    {"dms", "application/octet-stream"},\n    {"doc", "application/msword"},\n    {"docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"},\n    {"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},\n    {"docm","application/vnd.ms-word.document.macroEnabled.12"},\n    {"dotm","application/vnd.ms-word.template.macroEnabled.12"},\n    {"dtd", "application/xml-dtd"},\n    {"dv", "video/x-dv"},\n    {"dvi", "application/x-dvi"},\n    {"dxr", "application/x-director"},\n    {"eps", "application/postscript"},\n    {"etx", "text/x-setext"},\n    {"exe", "application/octet-stream"},\n    {"ez", "application/andrew-inset"},\n    {"gif", "image/gif"},\n    {"gram", "application/srgs"},\n    {"grxml", "application/srgs+xml"},\n    {"gtar", "application/x-gtar"},\n    {"hdf", "application/x-hdf"},\n    {"hqx", "application/mac-binhex40"},\n    {"htm", "text/html"},\n    {"html", "text/html"},\n    {"ice", "x-conference/x-cooltalk"},\n    {"ico", "image/x-icon"},\n    {"ics", "text/calendar"},\n    {"ief", "image/ief"},\n    {"ifb", "text/calendar"},\n    {"iges", "model/iges"},\n    {"igs", "model/iges"},\n    {"jnlp", "application/x-java-jnlp-file"},\n    {"jp2", "image/jp2"},\n    {"jpe", "image/jpeg"},\n    {"jpeg", "image/jpeg"},\n    {"jpg", "image/jpeg"},\n    {"js", "application/x-javascript"},\n    {"kar", "audio/midi"},\n    {"latex", "application/x-latex"},\n    {"lha", "application/octet-stream"},\n    {"lzh", "application/octet-stream"},\n    {"m3u", "audio/x-mpegurl"},\n    {"m4a", "audio/mp4a-latm"},\n    {"m4b", "audio/mp4a-latm"},\n    {"m4p", "audio/mp4a-latm"},\n    {"m4u", "video/vnd.mpegurl"},\n    {"m4v", "video/x-m4v"},\n    {"mac", "image/x-macpaint"},\n    {"man", "application/x-troff-man"},\n    {"mathml", "application/mathml+xml"},\n    {"me", "application/x-troff-me"},\n    {"mesh", "model/mesh"},\n    {"mid", "audio/midi"},\n    {"midi", "audio/midi"},\n    {"mif", "application/vnd.mif"},\n    {"mov", "video/quicktime"},\n    {"movie", "video/x-sgi-movie"},\n    {"mp2", "audio/mpeg"},\n    {"mp3", "audio/mpeg"},\n    {"mp4", "video/mp4"},\n    {"mpe", "video/mpeg"},\n    {"mpeg", "video/mpeg"},\n    {"mpg", "video/mpeg"},\n    {"mpga", "audio/mpeg"},\n    {"ms", "application/x-troff-ms"},\n    {"msh", "model/mesh"},\n    {"mxu", "video/vnd.mpegurl"},\n    {"nc", "application/x-netcdf"},\n    {"oda", "application/oda"},\n    {"ogg", "application/ogg"},\n    {"pbm", "image/x-portable-bitmap"},\n    {"pct", "image/pict"},\n    {"pdb", "chemical/x-pdb"},\n    {"pdf", "application/pdf"},\n    {"pgm", "image/x-portable-graymap"},\n    {"pgn", "application/x-chess-pgn"},\n    {"pic", "image/pict"},\n    {"pict", "image/pict"},\n    {"png", "image/png"}, \n    {"pnm", "image/x-portable-anymap"},\n    {"pnt", "image/x-macpaint"},\n    {"pntg", "image/x-macpaint"},\n    {"ppm", "image/x-portable-pixmap"},\n    {"ppt", "application/vnd.ms-powerpoint"},\n    {"pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"},\n    {"potx","application/vnd.openxmlformats-officedocument.presentationml.template"},\n    {"ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"},\n    {"ppam","application/vnd.ms-powerpoint.addin.macroEnabled.12"},\n    {"pptm","application/vnd.ms-powerpoint.presentation.macroEnabled.12"},\n    {"potm","application/vnd.ms-powerpoint.template.macroEnabled.12"},\n    {"ppsm","application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},\n    {"ps", "application/postscript"},\n    {"qt", "video/quicktime"},\n    {"qti", "image/x-quicktime"},\n    {"qtif", "image/x-quicktime"},\n    {"ra", "audio/x-pn-realaudio"},\n    {"ram", "audio/x-pn-realaudio"},\n    {"ras", "image/x-cmu-raster"},\n    {"rdf", "application/rdf+xml"},\n    {"rgb", "image/x-rgb"},\n    {"rm", "application/vnd.rn-realmedia"},\n    {"roff", "application/x-troff"},\n    {"rtf", "text/rtf"},\n    {"rtx", "text/richtext"},\n    {"sgm", "text/sgml"},\n    {"sgml", "text/sgml"},\n    {"sh", "application/x-sh"},\n    {"shar", "application/x-shar"},\n    {"silo", "model/mesh"},\n    {"sit", "application/x-stuffit"},\n    {"skd", "application/x-koan"},\n    {"skm", "application/x-koan"},\n    {"skp", "application/x-koan"},\n    {"skt", "application/x-koan"},\n    {"smi", "application/smil"},\n    {"smil", "application/smil"},\n    {"snd", "audio/basic"},\n    {"so", "application/octet-stream"},\n    {"spl", "application/x-futuresplash"},\n    {"src", "application/x-wais-source"},\n    {"sv4cpio", "application/x-sv4cpio"},\n    {"sv4crc", "application/x-sv4crc"},\n    {"svg", "image/svg+xml"},\n    {"swf", "application/x-shockwave-flash"},\n    {"t", "application/x-troff"},\n    {"tar", "application/x-tar"},\n    {"tcl", "application/x-tcl"},\n    {"tex", "application/x-tex"},\n    {"texi", "application/x-texinfo"},\n    {"texinfo", "application/x-texinfo"},\n    {"tif", "image/tiff"},\n    {"tiff", "image/tiff"},\n    {"tr", "application/x-troff"},\n    {"tsv", "text/tab-separated-values"},\n    {"txt", "text/plain"},\n    {"ustar", "application/x-ustar"},\n    {"vcd", "application/x-cdlink"},\n    {"vrml", "model/vrml"},\n    {"vxml", "application/voicexml+xml"},\n    {"wav", "audio/x-wav"},\n    {"wbmp", "image/vnd.wap.wbmp"},\n    {"wbmxl", "application/vnd.wap.wbxml"},\n    {"wml", "text/vnd.wap.wml"},\n    {"wmlc", "application/vnd.wap.wmlc"},\n    {"wmls", "text/vnd.wap.wmlscript"},\n    {"wmlsc", "application/vnd.wap.wmlscriptc"},\n    {"wrl", "model/vrml"},\n    {"xbm", "image/x-xbitmap"},\n    {"xht", "application/xhtml+xml"},\n    {"xhtml", "application/xhtml+xml"},\n    {"xls", "application/vnd.ms-excel"},                        \n    {"xml", "application/xml"},\n    {"xpm", "image/x-xpixmap"},\n    {"xsl", "application/xml"},\n    {"xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},\n    {"xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"},\n    {"xlsm","application/vnd.ms-excel.sheet.macroEnabled.12"},\n    {"xltm","application/vnd.ms-excel.template.macroEnabled.12"},\n    {"xlam","application/vnd.ms-excel.addin.macroEnabled.12"},\n    {"xlsb","application/vnd.ms-excel.sheet.binary.macroEnabled.12"},\n    {"xslt", "application/xslt+xml"},\n    {"xul", "application/vnd.mozilla.xul+xml"},\n    {"xwd", "image/x-xwindowdump"},\n    {"xyz", "chemical/x-xyz"},\n    {"zip", "application/zip"}\n  };\n\n  public static string GetMIMEType(string fileName)\n  {\n    //get file extension\n    string extension = Path.GetExtension(fileName).ToLowerInvariant();\n\n    if (extension.Length &gt; 0 &amp;&amp; \n        MIMETypesDictionary.ContainsKey(extension.Remove(0, 1)))\n    {\n      return MIMETypesDictionary[extension.Remove(0, 1)];\n    }\n    return "unknown/unknown";\n  }\n}\n</code></pre>\n'}, {'answer_id': 8051777, 'author': 'EvgeniySu', 'author_id': 1035766, 'author_profile': 'https://Stackoverflow.com/users/1035766', 'pm_score': 2, 'selected': False, 'text': '<p>I found this one useful.\nFor VB.NET developers:</p>\n\n<pre><code>    Public Shared Function GetFromFileName(ByVal fileName As String) As String\n        Return GetFromExtension(Path.GetExtension(fileName).Remove(0, 1))\n    End Function\n\n    Public Shared Function GetFromExtension(ByVal extension As String) As String\n        If extension.StartsWith("."c) Then\n            extension = extension.Remove(0, 1)\n        End If\n\n        If MIMETypesDictionary.ContainsKey(extension) Then\n            Return MIMETypesDictionary(extension)\n        End If\n\n        Return "unknown/unknown"\n    End Function\n\n    Private Shared ReadOnly MIMETypesDictionary As New Dictionary(Of String, String)() From { _\n         {"ai", "application/postscript"}, _\n         {"aif", "audio/x-aiff"}, _\n         {"aifc", "audio/x-aiff"}, _\n         {"aiff", "audio/x-aiff"}, _\n         {"asc", "text/plain"}, _\n         {"atom", "application/atom+xml"}, _\n         {"au", "audio/basic"}, _\n         {"avi", "video/x-msvideo"}, _\n         {"bcpio", "application/x-bcpio"}, _\n         {"bin", "application/octet-stream"}, _\n         {"bmp", "image/bmp"}, _\n         {"cdf", "application/x-netcdf"}, _\n         {"cgm", "image/cgm"}, _\n         {"class", "application/octet-stream"}, _\n         {"cpio", "application/x-cpio"}, _\n         {"cpt", "application/mac-compactpro"}, _\n         {"csh", "application/x-csh"}, _\n         {"css", "text/css"}, _\n         {"dcr", "application/x-director"}, _\n         {"dif", "video/x-dv"}, _\n         {"dir", "application/x-director"}, _\n         {"djv", "image/vnd.djvu"}, _\n         {"djvu", "image/vnd.djvu"}, _\n         {"dll", "application/octet-stream"}, _\n         {"dmg", "application/octet-stream"}, _\n         {"dms", "application/octet-stream"}, _\n         {"doc", "application/msword"}, _\n         {"dtd", "application/xml-dtd"}, _\n         {"dv", "video/x-dv"}, _\n         {"dvi", "application/x-dvi"}, _\n         {"dxr", "application/x-director"}, _\n         {"eps", "application/postscript"}, _\n         {"etx", "text/x-setext"}, _\n         {"exe", "application/octet-stream"}, _\n         {"ez", "application/andrew-inset"}, _\n         {"gif", "image/gif"}, _\n         {"gram", "application/srgs"}, _\n         {"grxml", "application/srgs+xml"}, _\n         {"gtar", "application/x-gtar"}, _\n         {"hdf", "application/x-hdf"}, _\n         {"hqx", "application/mac-binhex40"}, _\n         {"htm", "text/html"}, _\n         {"html", "text/html"}, _\n         {"ice", "x-conference/x-cooltalk"}, _\n         {"ico", "image/x-icon"}, _\n         {"ics", "text/calendar"}, _\n         {"ief", "image/ief"}, _\n         {"ifb", "text/calendar"}, _\n         {"iges", "model/iges"}, _\n         {"igs", "model/iges"}, _\n         {"jnlp", "application/x-java-jnlp-file"}, _\n         {"jp2", "image/jp2"}, _\n         {"jpe", "image/jpeg"}, _\n         {"jpeg", "image/jpeg"}, _\n         {"jpg", "image/jpeg"}, _\n         {"js", "application/x-javascript"}, _\n         {"kar", "audio/midi"}, _\n         {"latex", "application/x-latex"}, _\n         {"lha", "application/octet-stream"}, _\n         {"lzh", "application/octet-stream"}, _\n         {"m3u", "audio/x-mpegurl"}, _\n         {"m4a", "audio/mp4a-latm"}, _\n         {"m4b", "audio/mp4a-latm"}, _\n         {"m4p", "audio/mp4a-latm"}, _\n         {"m4u", "video/vnd.mpegurl"}, _\n         {"m4v", "video/x-m4v"}, _\n         {"mac", "image/x-macpaint"}, _\n         {"man", "application/x-troff-man"}, _\n         {"mathml", "application/mathml+xml"}, _\n         {"me", "application/x-troff-me"}, _\n         {"mesh", "model/mesh"}, _\n         {"mid", "audio/midi"}, _\n         {"midi", "audio/midi"}, _\n         {"mif", "application/vnd.mif"}, _\n         {"mov", "video/quicktime"}, _\n         {"movie", "video/x-sgi-movie"}, _\n         {"mp2", "audio/mpeg"}, _\n         {"mp3", "audio/mpeg"}, _\n         {"mp4", "video/mp4"}, _\n         {"mpe", "video/mpeg"}, _\n         {"mpeg", "video/mpeg"}, _\n         {"mpg", "video/mpeg"}, _\n         {"mpga", "audio/mpeg"}, _\n         {"ms", "application/x-troff-ms"}, _\n         {"msh", "model/mesh"}, _\n         {"mxu", "video/vnd.mpegurl"}, _\n         {"nc", "application/x-netcdf"}, _\n         {"oda", "application/oda"}, _\n         {"ogg", "application/ogg"}, _\n         {"pbm", "image/x-portable-bitmap"}, _\n         {"pct", "image/pict"}, _\n         {"pdb", "chemical/x-pdb"}, _\n         {"pdf", "application/pdf"}, _\n         {"pgm", "image/x-portable-graymap"}, _\n         {"pgn", "application/x-chess-pgn"}, _\n         {"pic", "image/pict"}, _\n         {"pict", "image/pict"}, _\n         {"png", "image/png"}, _\n         {"pnm", "image/x-portable-anymap"}, _\n         {"pnt", "image/x-macpaint"}, _\n         {"pntg", "image/x-macpaint"}, _\n         {"ppm", "image/x-portable-pixmap"}, _\n         {"ppt", "application/vnd.ms-powerpoint"}, _\n         {"ps", "application/postscript"}, _\n         {"qt", "video/quicktime"}, _\n         {"qti", "image/x-quicktime"}, _\n         {"qtif", "image/x-quicktime"}, _\n         {"ra", "audio/x-pn-realaudio"}, _\n         {"ram", "audio/x-pn-realaudio"}, _\n         {"ras", "image/x-cmu-raster"}, _\n         {"rdf", "application/rdf+xml"}, _\n         {"rgb", "image/x-rgb"}, _\n         {"rm", "application/vnd.rn-realmedia"}, _\n         {"roff", "application/x-troff"}, _\n         {"rtf", "text/rtf"}, _\n         {"rtx", "text/richtext"}, _\n         {"sgm", "text/sgml"}, _\n         {"sgml", "text/sgml"}, _\n         {"sh", "application/x-sh"}, _\n         {"shar", "application/x-shar"}, _\n         {"silo", "model/mesh"}, _\n         {"sit", "application/x-stuffit"}, _\n         {"skd", "application/x-koan"}, _\n         {"skm", "application/x-koan"}, _\n         {"skp", "application/x-koan"}, _\n         {"skt", "application/x-koan"}, _\n         {"smi", "application/smil"}, _\n         {"smil", "application/smil"}, _\n         {"snd", "audio/basic"}, _\n         {"so", "application/octet-stream"}, _\n         {"spl", "application/x-futuresplash"}, _\n         {"src", "application/x-wais-source"}, _\n         {"sv4cpio", "application/x-sv4cpio"}, _\n         {"sv4crc", "application/x-sv4crc"}, _\n         {"svg", "image/svg+xml"}, _\n         {"swf", "application/x-shockwave-flash"}, _\n         {"t", "application/x-troff"}, _\n         {"tar", "application/x-tar"}, _\n         {"tcl", "application/x-tcl"}, _\n         {"tex", "application/x-tex"}, _\n         {"texi", "application/x-texinfo"}, _\n         {"texinfo", "application/x-texinfo"}, _\n         {"tif", "image/tiff"}, _\n         {"tiff", "image/tiff"}, _\n         {"tr", "application/x-troff"}, _\n         {"tsv", "text/tab-separated-values"}, _\n         {"txt", "text/plain"}, _\n         {"ustar", "application/x-ustar"}, _\n         {"vcd", "application/x-cdlink"}, _\n         {"vrml", "model/vrml"}, _\n         {"vxml", "application/voicexml+xml"}, _\n         {"wav", "audio/x-wav"}, _\n         {"wbmp", "image/vnd.wap.wbmp"}, _\n         {"wbmxl", "application/vnd.wap.wbxml"}, _\n         {"wml", "text/vnd.wap.wml"}, _\n         {"wmlc", "application/vnd.wap.wmlc"}, _\n         {"wmls", "text/vnd.wap.wmlscript"}, _\n         {"wmlsc", "application/vnd.wap.wmlscriptc"}, _\n         {"wrl", "model/vrml"}, _\n         {"xbm", "image/x-xbitmap"}, _\n         {"xht", "application/xhtml+xml"}, _\n         {"xhtml", "application/xhtml+xml"}, _\n         {"xls", "application/vnd.ms-excel"}, _\n         {"xml", "application/xml"}, _\n         {"xpm", "image/x-xpixmap"}, _\n         {"xsl", "application/xml"}, _\n         {"xslt", "application/xslt+xml"}, _\n         {"xul", "application/vnd.mozilla.xul+xml"}, _\n         {"xwd", "image/x-xwindowdump"}, _\n         {"xyz", "chemical/x-xyz"}, _\n         {"zip", "application/zip"} _\n        }\n</code></pre>\n'}, {'answer_id': 9435701, 'author': 'CESAR CASTELLO BRANCO', 'author_id': 1231382, 'author_profile': 'https://Stackoverflow.com/users/1231382', 'pm_score': 3, 'selected': False, 'text': '<p>I use an hybrid solution:</p>\n\n<pre><code>    using System.Runtime.InteropServices;\n\n    [DllImport (@"urlmon.dll", CharSet = CharSet.Auto)]\n    private extern static System.UInt32 FindMimeFromData(\n        System.UInt32 pBC, \n        [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,\n        [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,\n        System.UInt32 cbSize,\n        [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,\n        System.UInt32 dwMimeFlags,\n        out System.UInt32 ppwzMimeOut,\n        System.UInt32 dwReserverd\n    );\n\n    private string GetMimeFromRegistry (string Filename)\n    {\n        string mime = "application/octetstream";\n        string ext = System.IO.Path.GetExtension(Filename).ToLower();\n        Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);\n        if (rk != null &amp;&amp; rk.GetValue("Content Type") != null)\n            mime = rk.GetValue("Content Type").ToString();\n        return mime;\n    }\n\n    public string GetMimeTypeFromFileAndRegistry (string filename)\n    {\n        if (!File.Exists(filename))\n        {\n           return GetMimeFromRegistry (filename);\n        }\n\n        byte[] buffer = new byte[256];\n\n        using (FileStream fs = new FileStream(filename, FileMode.Open))\n        {\n            if (fs.Length &gt;= 256)\n                fs.Read(buffer, 0, 256);\n            else\n                fs.Read(buffer, 0, (int)fs.Length);\n        }\n\n        try\n        {            \n            System.UInt32 mimetype;\n\n            FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);\n\n            System.IntPtr mimeTypePtr = new IntPtr(mimetype);\n\n            string mime = Marshal.PtrToStringUni(mimeTypePtr);\n\n            Marshal.FreeCoTaskMem(mimeTypePtr);\n\n            if (string.IsNullOrWhiteSpace (mime) || \n                mime =="text/plain" || mime == "application/octet-stream")                    \n            {\n                return GetMimeFromRegistry (filename);\n            }\n\n            return mime;\n        }\n        catch (Exception e)\n        {\n            return GetMimeFromRegistry (filename);\n        }\n    }\n</code></pre>\n'}, {'answer_id': 12229156, 'author': 'Bitmapped', 'author_id': 1426652, 'author_profile': 'https://Stackoverflow.com/users/1426652', 'pm_score': 5, 'selected': False, 'text': '<p>If you\'re using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note that this uses the file extension, not data in the file itself.</p>\n\n<p>Documentation is at <a href="http://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping</a></p>\n'}, {'answer_id': 13504977, 'author': 'Matthew Lock', 'author_id': 74585, 'author_profile': 'https://Stackoverflow.com/users/74585', 'pm_score': 2, 'selected': False, 'text': '<p>If someone was up for it they could port the excellent perl module <a href="http://search.cpan.org/~pmison/File-Type-0.22/lib/File/Type.pm" rel="nofollow">File::Type</a> to .NET. In the code is a set of file header magic number look ups for each file type or regex matches.</p>\n\n<p>Here\'s a .NET file type detecting library <a href="http://filetypedetective.codeplex.com/" rel="nofollow">http://filetypedetective.codeplex.com/</a> but it only detects a smallish number of files at the moment.</p>\n'}, {'answer_id': 13614746, 'author': 'Gaff', 'author_id': 695874, 'author_profile': 'https://Stackoverflow.com/users/695874', 'pm_score': 7, 'selected': False, 'text': '<p>Edit: Just use <a href="https://github.com/Muraad/Mime-Detective">Mime Detective</a></p>\n\n<p>I use byte array sequences to determine the correct MIME type of a given file. The advantage of this over just looking at the file extension of the file name is that if a user were to rename a file to bypass certain file type upload restrictions, the file name extension would fail to catch this. On the other hand, getting the file signature via byte array will stop this mischievous behavior from happening.</p>\n\n<p>Here is an example in C#:</p>\n\n<pre><code>public class MimeType\n{\n    private static readonly byte[] BMP = { 66, 77 };\n    private static readonly byte[] DOC = { 208, 207, 17, 224, 161, 177, 26, 225 };\n    private static readonly byte[] EXE_DLL = { 77, 90 };\n    private static readonly byte[] GIF = { 71, 73, 70, 56 };\n    private static readonly byte[] ICO = { 0, 0, 1, 0 };\n    private static readonly byte[] JPG = { 255, 216, 255 };\n    private static readonly byte[] MP3 = { 255, 251, 48 };\n    private static readonly byte[] OGG = { 79, 103, 103, 83, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 };\n    private static readonly byte[] PDF = { 37, 80, 68, 70, 45, 49, 46 };\n    private static readonly byte[] PNG = { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 };\n    private static readonly byte[] RAR = { 82, 97, 114, 33, 26, 7, 0 };\n    private static readonly byte[] SWF = { 70, 87, 83 };\n    private static readonly byte[] TIFF = { 73, 73, 42, 0 };\n    private static readonly byte[] TORRENT = { 100, 56, 58, 97, 110, 110, 111, 117, 110, 99, 101 };\n    private static readonly byte[] TTF = { 0, 1, 0, 0, 0 };\n    private static readonly byte[] WAV_AVI = { 82, 73, 70, 70 };\n    private static readonly byte[] WMV_WMA = { 48, 38, 178, 117, 142, 102, 207, 17, 166, 217, 0, 170, 0, 98, 206, 108 };\n    private static readonly byte[] ZIP_DOCX = { 80, 75, 3, 4 };\n\n    public static string GetMimeType(byte[] file, string fileName)\n    {\n\n        string mime = "application/octet-stream"; //DEFAULT UNKNOWN MIME TYPE\n\n        //Ensure that the filename isn\'t empty or null\n        if (string.IsNullOrWhiteSpace(fileName))\n        {\n            return mime;\n        }\n\n        //Get the file extension\n        string extension = Path.GetExtension(fileName) == null\n                               ? string.Empty\n                               : Path.GetExtension(fileName).ToUpper();\n\n        //Get the MIME Type\n        if (file.Take(2).SequenceEqual(BMP))\n        {\n            mime = "image/bmp";\n        }\n        else if (file.Take(8).SequenceEqual(DOC))\n        {\n            mime = "application/msword";\n        }\n        else if (file.Take(2).SequenceEqual(EXE_DLL))\n        {\n            mime = "application/x-msdownload"; //both use same mime type\n        }\n        else if (file.Take(4).SequenceEqual(GIF))\n        {\n            mime = "image/gif";\n        }\n        else if (file.Take(4).SequenceEqual(ICO))\n        {\n            mime = "image/x-icon";\n        }\n        else if (file.Take(3).SequenceEqual(JPG))\n        {\n            mime = "image/jpeg";\n        }\n        else if (file.Take(3).SequenceEqual(MP3))\n        {\n            mime = "audio/mpeg";\n        }\n        else if (file.Take(14).SequenceEqual(OGG))\n        {\n            if (extension == ".OGX")\n            {\n                mime = "application/ogg";\n            }\n            else if (extension == ".OGA")\n            {\n                mime = "audio/ogg";\n            }\n            else\n            {\n                mime = "video/ogg";\n            }\n        }\n        else if (file.Take(7).SequenceEqual(PDF))\n        {\n            mime = "application/pdf";\n        }\n        else if (file.Take(16).SequenceEqual(PNG))\n        {\n            mime = "image/png";\n        }\n        else if (file.Take(7).SequenceEqual(RAR))\n        {\n            mime = "application/x-rar-compressed";\n        }\n        else if (file.Take(3).SequenceEqual(SWF))\n        {\n            mime = "application/x-shockwave-flash";\n        }\n        else if (file.Take(4).SequenceEqual(TIFF))\n        {\n            mime = "image/tiff";\n        }\n        else if (file.Take(11).SequenceEqual(TORRENT))\n        {\n            mime = "application/x-bittorrent";\n        }\n        else if (file.Take(5).SequenceEqual(TTF))\n        {\n            mime = "application/x-font-ttf";\n        }\n        else if (file.Take(4).SequenceEqual(WAV_AVI))\n        {\n            mime = extension == ".AVI" ? "video/x-msvideo" : "audio/x-wav";\n        }\n        else if (file.Take(16).SequenceEqual(WMV_WMA))\n        {\n            mime = extension == ".WMA" ? "audio/x-ms-wma" : "video/x-ms-wmv";\n        }\n        else if (file.Take(4).SequenceEqual(ZIP_DOCX))\n        {\n            mime = extension == ".DOCX" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "application/x-zip-compressed";\n        }\n\n        return mime;\n    }\n\n\n}\n</code></pre>\n\n<p>Notice I handled DOCX file types differently since DOCX is really just a ZIP file. In this scenario, I simply check the file extension once I verified that it has that sequence. This example is far from complete for some people, but you can easily add your own.</p>\n\n<p>If you want to add more MIME types, you can get the byte array sequences of many different file types <a href="http://www.mircscripts.org/showdoc.php?type=code&amp;id=2933">from here</a>. Also, <a href="http://www.garykessler.net/library/file_sigs.html">here is another good resource</a> concerning file signatures. </p>\n\n<p>What I do a lot of times if all else fails is step through several files of a particular type that I am looking for and look for a pattern in the byte sequence of the files. In the end, this is still basic verification and cannot be used for 100% proof of determining file types.</p>\n'}, {'answer_id': 15236493, 'author': 'warrior', 'author_id': 1880844, 'author_profile': 'https://Stackoverflow.com/users/1880844', 'pm_score': 1, 'selected': False, 'text': '<p>IIS 7 or more</p>\n\n<p>Use this code, but you need to be the admin on the server</p>\n\n<pre><code>public bool CheckMimeMapExtension(string fileExtension)\n        {\n            try\n            {\n\n                using (\n                ServerManager serverManager = new ServerManager())\n                {   \n                    // connects to default app.config\n                    var config = serverManager.GetApplicationHostConfiguration();\n                    var staticContent = config.GetSection("system.webServer/staticContent");\n                    var mimeMap = staticContent.GetCollection();\n\n                    foreach (var mimeType in mimeMap)\n                    {\n\n                        if (((String)mimeType["fileExtension"]).Equals(fileExtension, StringComparison.OrdinalIgnoreCase))\n                            return true;\n\n                    }\n\n                }\n                return false;\n            }\n            catch (Exception ex)\n            { \n                Console.WriteLine("An exception has occurred: \\n{0}", ex.Message);\n                Console.Read();\n            }\n\n            return false;\n\n        }\n</code></pre>\n'}, {'answer_id': 16469313, 'author': 'Frederick Samson', 'author_id': 2099690, 'author_profile': 'https://Stackoverflow.com/users/2099690', 'pm_score': 2, 'selected': False, 'text': '<p>This class use previous answers to try in 3 different ways: harcoded based on extension, FindMimeFromData API and using registry.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Runtime.InteropServices;\n\nusing Microsoft.Win32;\n\nnamespace YourNamespace\n{\n    public static class MimeTypeParser\n    {\n        [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]\n        private extern static System.UInt32 FindMimeFromData(\n                System.UInt32 pBC,\n                [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,\n                [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,\n                System.UInt32 cbSize,\n                [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,\n                System.UInt32 dwMimeFlags,\n                out System.UInt32 ppwzMimeOut,\n                System.UInt32 dwReserverd\n        );\n\n        public static string GetMimeType(string sFilePath)\n        {\n            string sMimeType = GetMimeTypeFromList(sFilePath);\n\n            if (String.IsNullOrEmpty(sMimeType))\n            {\n                sMimeType = GetMimeTypeFromFile(sFilePath);\n\n                if (String.IsNullOrEmpty(sMimeType))\n                {\n                    sMimeType = GetMimeTypeFromRegistry(sFilePath);\n                }\n            }\n\n            return sMimeType;\n        }\n\n        public static string GetMimeTypeFromList(string sFileNameOrPath)\n        {\n            string sMimeType = null;\n            string sExtensionWithoutDot = Path.GetExtension(sFileNameOrPath).Substring(1).ToLower();\n\n            if (!String.IsNullOrEmpty(sExtensionWithoutDot) &amp;&amp; spDicMIMETypes.ContainsKey(sExtensionWithoutDot))\n            {\n                sMimeType = spDicMIMETypes[sExtensionWithoutDot];\n            }\n\n            return sMimeType;\n        }\n\n        public static string GetMimeTypeFromRegistry(string sFileNameOrPath)\n        {\n            string sMimeType = null;\n            string sExtension = Path.GetExtension(sFileNameOrPath).ToLower();\n            RegistryKey pKey = Registry.ClassesRoot.OpenSubKey(sExtension);\n\n            if (pKey != null &amp;&amp; pKey.GetValue("Content Type") != null)\n            {\n                sMimeType = pKey.GetValue("Content Type").ToString();\n            }\n\n            return sMimeType;\n        }\n\n        public static string GetMimeTypeFromFile(string sFilePath)\n        {\n            string sMimeType = null;\n\n            if (File.Exists(sFilePath))\n            {\n                byte[] abytBuffer = new byte[256];\n\n                using (FileStream pFileStream = new FileStream(sFilePath, FileMode.Open))\n                {\n                    if (pFileStream.Length &gt;= 256)\n                    {\n                        pFileStream.Read(abytBuffer, 0, 256);\n                    }\n                    else\n                    {\n                        pFileStream.Read(abytBuffer, 0, (int)pFileStream.Length);\n                    }\n                }\n\n                try\n                {\n                    UInt32 unMimeType;\n\n                    FindMimeFromData(0, null, abytBuffer, 256, null, 0, out unMimeType, 0);\n\n                    IntPtr pMimeType = new IntPtr(unMimeType);\n                    string sMimeTypeFromFile = Marshal.PtrToStringUni(pMimeType);\n\n                    Marshal.FreeCoTaskMem(pMimeType);\n\n                    if (!String.IsNullOrEmpty(sMimeTypeFromFile) &amp;&amp; sMimeTypeFromFile != "text/plain" &amp;&amp; sMimeTypeFromFile != "application/octet-stream")\n                    {\n                        sMimeType = sMimeTypeFromFile;\n                    }\n                }\n                catch {}\n            }\n\n            return sMimeType;\n        }\n\n        private static readonly Dictionary&lt;string, string&gt; spDicMIMETypes = new Dictionary&lt;string, string&gt;\n        {\n            {"ai", "application/postscript"},\n            {"aif", "audio/x-aiff"},\n            {"aifc", "audio/x-aiff"},\n            {"aiff", "audio/x-aiff"},\n            {"asc", "text/plain"},\n            {"atom", "application/atom+xml"},\n            {"au", "audio/basic"},\n            {"avi", "video/x-msvideo"},\n            {"bcpio", "application/x-bcpio"},\n            {"bin", "application/octet-stream"},\n            {"bmp", "image/bmp"},\n            {"cdf", "application/x-netcdf"},\n            {"cgm", "image/cgm"},\n            {"class", "application/octet-stream"},\n            {"cpio", "application/x-cpio"},\n            {"cpt", "application/mac-compactpro"},\n            {"csh", "application/x-csh"},\n            {"css", "text/css"},\n            {"dcr", "application/x-director"},\n            {"dif", "video/x-dv"},\n            {"dir", "application/x-director"},\n            {"djv", "image/vnd.djvu"},\n            {"djvu", "image/vnd.djvu"},\n            {"dll", "application/octet-stream"},\n            {"dmg", "application/octet-stream"},\n            {"dms", "application/octet-stream"},\n            {"doc", "application/msword"},\n            {"docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"},\n            {"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},\n            {"docm","application/vnd.ms-word.document.macroEnabled.12"},\n            {"dotm","application/vnd.ms-word.template.macroEnabled.12"},\n            {"dtd", "application/xml-dtd"},\n            {"dv", "video/x-dv"},\n            {"dvi", "application/x-dvi"},\n            {"dxr", "application/x-director"},\n            {"eps", "application/postscript"},\n            {"etx", "text/x-setext"},\n            {"exe", "application/octet-stream"},\n            {"ez", "application/andrew-inset"},\n            {"gif", "image/gif"},\n            {"gram", "application/srgs"},\n            {"grxml", "application/srgs+xml"},\n            {"gtar", "application/x-gtar"},\n            {"hdf", "application/x-hdf"},\n            {"hqx", "application/mac-binhex40"},\n            {"htc", "text/x-component"},\n            {"htm", "text/html"},\n            {"html", "text/html"},\n            {"ice", "x-conference/x-cooltalk"},\n            {"ico", "image/x-icon"},\n            {"ics", "text/calendar"},\n            {"ief", "image/ief"},\n            {"ifb", "text/calendar"},\n            {"iges", "model/iges"},\n            {"igs", "model/iges"},\n            {"jnlp", "application/x-java-jnlp-file"},\n            {"jp2", "image/jp2"},\n            {"jpe", "image/jpeg"},\n            {"jpeg", "image/jpeg"},\n            {"jpg", "image/jpeg"},\n            {"js", "application/x-javascript"},\n            {"kar", "audio/midi"},\n            {"latex", "application/x-latex"},\n            {"lha", "application/octet-stream"},\n            {"lzh", "application/octet-stream"},\n            {"m3u", "audio/x-mpegurl"},\n            {"m4a", "audio/mp4a-latm"},\n            {"m4b", "audio/mp4a-latm"},\n            {"m4p", "audio/mp4a-latm"},\n            {"m4u", "video/vnd.mpegurl"},\n            {"m4v", "video/x-m4v"},\n            {"mac", "image/x-macpaint"},\n            {"man", "application/x-troff-man"},\n            {"mathml", "application/mathml+xml"},\n            {"me", "application/x-troff-me"},\n            {"mesh", "model/mesh"},\n            {"mid", "audio/midi"},\n            {"midi", "audio/midi"},\n            {"mif", "application/vnd.mif"},\n            {"mov", "video/quicktime"},\n            {"movie", "video/x-sgi-movie"},\n            {"mp2", "audio/mpeg"},\n            {"mp3", "audio/mpeg"},\n            {"mp4", "video/mp4"},\n            {"mpe", "video/mpeg"},\n            {"mpeg", "video/mpeg"},\n            {"mpg", "video/mpeg"},\n            {"mpga", "audio/mpeg"},\n            {"ms", "application/x-troff-ms"},\n            {"msh", "model/mesh"},\n            {"mxu", "video/vnd.mpegurl"},\n            {"nc", "application/x-netcdf"},\n            {"oda", "application/oda"},\n            {"ogg", "application/ogg"},\n            {"pbm", "image/x-portable-bitmap"},\n            {"pct", "image/pict"},\n            {"pdb", "chemical/x-pdb"},\n            {"pdf", "application/pdf"},\n            {"pgm", "image/x-portable-graymap"},\n            {"pgn", "application/x-chess-pgn"},\n            {"pic", "image/pict"},\n            {"pict", "image/pict"},\n            {"png", "image/png"}, \n            {"pnm", "image/x-portable-anymap"},\n            {"pnt", "image/x-macpaint"},\n            {"pntg", "image/x-macpaint"},\n            {"ppm", "image/x-portable-pixmap"},\n            {"ppt", "application/vnd.ms-powerpoint"},\n            {"pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"},\n            {"potx","application/vnd.openxmlformats-officedocument.presentationml.template"},\n            {"ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"},\n            {"ppam","application/vnd.ms-powerpoint.addin.macroEnabled.12"},\n            {"pptm","application/vnd.ms-powerpoint.presentation.macroEnabled.12"},\n            {"potm","application/vnd.ms-powerpoint.template.macroEnabled.12"},\n            {"ppsm","application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},\n            {"ps", "application/postscript"},\n            {"qt", "video/quicktime"},\n            {"qti", "image/x-quicktime"},\n            {"qtif", "image/x-quicktime"},\n            {"ra", "audio/x-pn-realaudio"},\n            {"ram", "audio/x-pn-realaudio"},\n            {"ras", "image/x-cmu-raster"},\n            {"rdf", "application/rdf+xml"},\n            {"rgb", "image/x-rgb"},\n            {"rm", "application/vnd.rn-realmedia"},\n            {"roff", "application/x-troff"},\n            {"rtf", "text/rtf"},\n            {"rtx", "text/richtext"},\n            {"sgm", "text/sgml"},\n            {"sgml", "text/sgml"},\n            {"sh", "application/x-sh"},\n            {"shar", "application/x-shar"},\n            {"silo", "model/mesh"},\n            {"sit", "application/x-stuffit"},\n            {"skd", "application/x-koan"},\n            {"skm", "application/x-koan"},\n            {"skp", "application/x-koan"},\n            {"skt", "application/x-koan"},\n            {"smi", "application/smil"},\n            {"smil", "application/smil"},\n            {"snd", "audio/basic"},\n            {"so", "application/octet-stream"},\n            {"spl", "application/x-futuresplash"},\n            {"src", "application/x-wais-source"},\n            {"sv4cpio", "application/x-sv4cpio"},\n            {"sv4crc", "application/x-sv4crc"},\n            {"svg", "image/svg+xml"},\n            {"swf", "application/x-shockwave-flash"},\n            {"t", "application/x-troff"},\n            {"tar", "application/x-tar"},\n            {"tcl", "application/x-tcl"},\n            {"tex", "application/x-tex"},\n            {"texi", "application/x-texinfo"},\n            {"texinfo", "application/x-texinfo"},\n            {"tif", "image/tiff"},\n            {"tiff", "image/tiff"},\n            {"tr", "application/x-troff"},\n            {"tsv", "text/tab-separated-values"},\n            {"txt", "text/plain"},\n            {"ustar", "application/x-ustar"},\n            {"vcd", "application/x-cdlink"},\n            {"vrml", "model/vrml"},\n            {"vxml", "application/voicexml+xml"},\n            {"wav", "audio/x-wav"},\n            {"wbmp", "image/vnd.wap.wbmp"},\n            {"wbmxl", "application/vnd.wap.wbxml"},\n            {"wml", "text/vnd.wap.wml"},\n            {"wmlc", "application/vnd.wap.wmlc"},\n            {"wmls", "text/vnd.wap.wmlscript"},\n            {"wmlsc", "application/vnd.wap.wmlscriptc"},\n            {"wrl", "model/vrml"},\n            {"xbm", "image/x-xbitmap"},\n            {"xht", "application/xhtml+xml"},\n            {"xhtml", "application/xhtml+xml"},\n            {"xls", "application/vnd.ms-excel"},                                                \n            {"xml", "application/xml"},\n            {"xpm", "image/x-xpixmap"},\n            {"xsl", "application/xml"},\n            {"xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},\n            {"xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"},\n            {"xlsm","application/vnd.ms-excel.sheet.macroEnabled.12"},\n            {"xltm","application/vnd.ms-excel.template.macroEnabled.12"},\n            {"xlam","application/vnd.ms-excel.addin.macroEnabled.12"},\n            {"xlsb","application/vnd.ms-excel.sheet.binary.macroEnabled.12"},\n            {"xslt", "application/xslt+xml"},\n            {"xul", "application/vnd.mozilla.xul+xml"},\n            {"xwd", "image/x-xwindowdump"},\n            {"xyz", "chemical/x-xyz"},\n            {"zip", "application/zip"}\n        };\n    }\n}\n</code></pre>\n'}, {'answer_id': 19401456, 'author': 'Ognyan Dimitrov', 'author_id': 1042934, 'author_profile': 'https://Stackoverflow.com/users/1042934', 'pm_score': 0, 'selected': False, 'text': '<p>When working with Windows Azure Web role or any other host that runs your app in Limited Trust do not forget that you will not be allowed to access registry or unmanaged code. Hybrid approach - combination of try-catch-for-registry and in-memory dictionary looks like a good solution that has a bit of everything. </p>\n\n<p>I use this code to do it : </p>\n\n<pre><code>public class DefaultMimeResolver : IMimeResolver\n{\n    private readonly IFileRepository _fileRepository;\n\n    public DefaultMimeResolver(IFileRepository fileRepository)\n    {\n        _fileRepository = fileRepository;\n    }\n\n    [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]\n    private static extern System.UInt32 FindMimeFromData(\n        System.UInt32 pBC, [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,\n         [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,\n         System.UInt32 cbSize,\n         [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,\n         System.UInt32 dwMimeFlags,\n         out System.UInt32 ppwzMimeOut,\n         System.UInt32 dwReserverd);\n\n\n    public string GetMimeTypeFromFileExtension(string fileExtension)\n    {\n        if (string.IsNullOrEmpty(fileExtension))\n        {\n            throw new ArgumentNullException("fileExtension");\n        }\n\n        string mimeType = GetMimeTypeFromList(fileExtension);\n\n        if (String.IsNullOrEmpty(mimeType))\n        {\n            mimeType = GetMimeTypeFromRegistry(fileExtension);\n        }\n\n        return mimeType;\n    }\n\n    public string GetMimeTypeFromFile(string filePath)\n    {\n        if (string.IsNullOrEmpty(filePath))\n        {\n            throw new ArgumentNullException("filePath");\n        }\n\n        if (!File.Exists(filePath))\n        {\n            throw new FileNotFoundException("File not found : ", filePath);\n        }\n\n        string mimeType = GetMimeTypeFromList(Path.GetExtension(filePath).ToLower());\n\n        if (String.IsNullOrEmpty(mimeType))\n        {\n            mimeType = GetMimeTypeFromRegistry(Path.GetExtension(filePath).ToLower());\n\n            if (String.IsNullOrEmpty(mimeType))\n            {\n                mimeType = GetMimeTypeFromFileInternal(filePath);\n            }\n        }\n\n        return mimeType;\n    }\n\n    private string GetMimeTypeFromList(string fileExtension)\n    {\n        string mimeType = null;\n\n        if (fileExtension.StartsWith("."))\n        {\n            fileExtension = fileExtension.TrimStart(\'.\');\n        }\n\n        if (!String.IsNullOrEmpty(fileExtension) &amp;&amp; _mimeTypes.ContainsKey(fileExtension))\n        {\n            mimeType = _mimeTypes[fileExtension];\n        }\n\n        return mimeType;\n    }\n\n    private string GetMimeTypeFromRegistry(string fileExtension)\n    {\n        string mimeType = null;\n        try\n        {\n            RegistryKey key = Registry.ClassesRoot.OpenSubKey(fileExtension);\n\n            if (key != null &amp;&amp; key.GetValue("Content Type") != null)\n            {\n                mimeType = key.GetValue("Content Type").ToString();\n            }\n        }\n        catch (Exception)\n        {\n            // Empty. When this code is running in limited mode accessing registry is not allowed.\n        }\n\n        return mimeType;\n    }\n\n    private string GetMimeTypeFromFileInternal(string filePath)\n    {\n        string mimeType = null;\n\n        if (!File.Exists(filePath))\n        {\n            return null;\n        }\n\n        byte[] byteBuffer = new byte[256];\n\n        using (FileStream fileStream = _fileRepository.Get(filePath))\n        {\n            if (fileStream.Length &gt;= 256)\n            {\n                fileStream.Read(byteBuffer, 0, 256);\n            }\n            else\n            {\n                fileStream.Read(byteBuffer, 0, (int)fileStream.Length);\n            }\n        }\n\n        try\n        {\n            UInt32 MimeTypeNum;\n\n            FindMimeFromData(0, null, byteBuffer, 256, null, 0, out MimeTypeNum, 0);\n\n            IntPtr mimeTypePtr = new IntPtr(MimeTypeNum);\n            string mimeTypeFromFile = Marshal.PtrToStringUni(mimeTypePtr);\n\n            Marshal.FreeCoTaskMem(mimeTypePtr);\n\n            if (!String.IsNullOrEmpty(mimeTypeFromFile) &amp;&amp; mimeTypeFromFile != "text/plain" &amp;&amp; mimeTypeFromFile != "application/octet-stream")\n            {\n                mimeType = mimeTypeFromFile;\n            }\n        }\n        catch\n        {\n            // Empty. \n        }\n\n        return mimeType;\n    }\n\n    private readonly Dictionary&lt;string, string&gt; _mimeTypes = new Dictionary&lt;string, string&gt;\n        {\n            {"ai", "application/postscript"},\n            {"aif", "audio/x-aiff"},\n            {"aifc", "audio/x-aiff"},\n            {"aiff", "audio/x-aiff"},\n            {"asc", "text/plain"},\n            {"atom", "application/atom+xml"},\n            {"au", "audio/basic"},\n            {"avi", "video/x-msvideo"},\n            {"bcpio", "application/x-bcpio"},\n            {"bin", "application/octet-stream"},\n            {"bmp", "image/bmp"},\n            {"cdf", "application/x-netcdf"},\n            {"cgm", "image/cgm"},\n            {"class", "application/octet-stream"},\n            {"cpio", "application/x-cpio"},\n            {"cpt", "application/mac-compactpro"},\n            {"csh", "application/x-csh"},\n            {"css", "text/css"},\n            {"dcr", "application/x-director"},\n            {"dif", "video/x-dv"},\n            {"dir", "application/x-director"},\n            {"djv", "image/vnd.djvu"},\n            {"djvu", "image/vnd.djvu"},\n            {"dll", "application/octet-stream"},\n            {"dmg", "application/octet-stream"},\n            {"dms", "application/octet-stream"},\n            {"doc", "application/msword"},\n            {"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},\n            {"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},\n            {"docm", "application/vnd.ms-word.document.macroEnabled.12"},\n            {"dotm", "application/vnd.ms-word.template.macroEnabled.12"},\n            {"dtd", "application/xml-dtd"},\n            {"dv", "video/x-dv"},\n            {"dvi", "application/x-dvi"},\n            {"dxr", "application/x-director"},\n            {"eps", "application/postscript"},\n            {"etx", "text/x-setext"},\n            {"exe", "application/octet-stream"},\n            {"ez", "application/andrew-inset"},\n            {"gif", "image/gif"},\n            {"gram", "application/srgs"},\n            {"grxml", "application/srgs+xml"},\n            {"gtar", "application/x-gtar"},\n            {"hdf", "application/x-hdf"},\n            {"hqx", "application/mac-binhex40"},\n            {"htc", "text/x-component"},\n            {"htm", "text/html"},\n            {"html", "text/html"},\n            {"ice", "x-conference/x-cooltalk"},\n            {"ico", "image/x-icon"},\n            {"ics", "text/calendar"},\n            {"ief", "image/ief"},\n            {"ifb", "text/calendar"},\n            {"iges", "model/iges"},\n            {"igs", "model/iges"},\n            {"jnlp", "application/x-java-jnlp-file"},\n            {"jp2", "image/jp2"},\n            {"jpe", "image/jpeg"},\n            {"jpeg", "image/jpeg"},\n            {"jpg", "image/jpeg"},\n            {"js", "application/x-javascript"},\n            {"kar", "audio/midi"},\n            {"latex", "application/x-latex"},\n            {"lha", "application/octet-stream"},\n            {"lzh", "application/octet-stream"},\n            {"m3u", "audio/x-mpegurl"},\n            {"m4a", "audio/mp4a-latm"},\n            {"m4b", "audio/mp4a-latm"},\n            {"m4p", "audio/mp4a-latm"},\n            {"m4u", "video/vnd.mpegurl"},\n            {"m4v", "video/x-m4v"},\n            {"mac", "image/x-macpaint"},\n            {"man", "application/x-troff-man"},\n            {"mathml", "application/mathml+xml"},\n            {"me", "application/x-troff-me"},\n            {"mesh", "model/mesh"},\n            {"mid", "audio/midi"},\n            {"midi", "audio/midi"},\n            {"mif", "application/vnd.mif"},\n            {"mov", "video/quicktime"},\n            {"movie", "video/x-sgi-movie"},\n            {"mp2", "audio/mpeg"},\n            {"mp3", "audio/mpeg"},\n            {"mp4", "video/mp4"},\n            {"mpe", "video/mpeg"},\n            {"mpeg", "video/mpeg"},\n            {"mpg", "video/mpeg"},\n            {"mpga", "audio/mpeg"},\n            {"ms", "application/x-troff-ms"},\n            {"msh", "model/mesh"},\n            {"mxu", "video/vnd.mpegurl"},\n            {"nc", "application/x-netcdf"},\n            {"oda", "application/oda"},\n            {"ogg", "application/ogg"},\n            {"pbm", "image/x-portable-bitmap"},\n            {"pct", "image/pict"},\n            {"pdb", "chemical/x-pdb"},\n            {"pdf", "application/pdf"},\n            {"pgm", "image/x-portable-graymap"},\n            {"pgn", "application/x-chess-pgn"},\n            {"pic", "image/pict"},\n            {"pict", "image/pict"},\n            {"png", "image/png"},\n            {"pnm", "image/x-portable-anymap"},\n            {"pnt", "image/x-macpaint"},\n            {"pntg", "image/x-macpaint"},\n            {"ppm", "image/x-portable-pixmap"},\n            {"ppt", "application/vnd.ms-powerpoint"},\n            {"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},\n            {"potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},\n            {"ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},\n            {"ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},\n            {"pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},\n            {"potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},\n            {"ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},\n            {"ps", "application/postscript"},\n            {"qt", "video/quicktime"},\n            {"qti", "image/x-quicktime"},\n            {"qtif", "image/x-quicktime"},\n            {"ra", "audio/x-pn-realaudio"},\n            {"ram", "audio/x-pn-realaudio"},\n            {"ras", "image/x-cmu-raster"},\n            {"rdf", "application/rdf+xml"},\n            {"rgb", "image/x-rgb"},\n            {"rm", "application/vnd.rn-realmedia"},\n            {"roff", "application/x-troff"},\n            {"rtf", "text/rtf"},\n            {"rtx", "text/richtext"},\n            {"sgm", "text/sgml"},\n            {"sgml", "text/sgml"},\n            {"sh", "application/x-sh"},\n            {"shar", "application/x-shar"},\n            {"silo", "model/mesh"},\n            {"sit", "application/x-stuffit"},\n            {"skd", "application/x-koan"},\n            {"skm", "application/x-koan"},\n            {"skp", "application/x-koan"},\n            {"skt", "application/x-koan"},\n            {"smi", "application/smil"},\n            {"smil", "application/smil"},\n            {"snd", "audio/basic"},\n            {"so", "application/octet-stream"},\n            {"spl", "application/x-futuresplash"},\n            {"src", "application/x-wais-source"},\n            {"sv4cpio", "application/x-sv4cpio"},\n            {"sv4crc", "application/x-sv4crc"},\n            {"svg", "image/svg+xml"},\n            {"swf", "application/x-shockwave-flash"},\n            {"t", "application/x-troff"},\n            {"tar", "application/x-tar"},\n            {"tcl", "application/x-tcl"},\n            {"tex", "application/x-tex"},\n            {"texi", "application/x-texinfo"},\n            {"texinfo", "application/x-texinfo"},\n            {"tif", "image/tiff"},\n            {"tiff", "image/tiff"},\n            {"tr", "application/x-troff"},\n            {"tsv", "text/tab-separated-values"},\n            {"txt", "text/plain"},\n            {"ustar", "application/x-ustar"},\n            {"vcd", "application/x-cdlink"},\n            {"vrml", "model/vrml"},\n            {"vxml", "application/voicexml+xml"},\n            {"wav", "audio/x-wav"},\n            {"wbmp", "image/vnd.wap.wbmp"},\n            {"wbmxl", "application/vnd.wap.wbxml"},\n            {"wml", "text/vnd.wap.wml"},\n            {"wmlc", "application/vnd.wap.wmlc"},\n            {"wmls", "text/vnd.wap.wmlscript"},\n            {"wmlsc", "application/vnd.wap.wmlscriptc"},\n            {"wrl", "model/vrml"},\n            {"xbm", "image/x-xbitmap"},\n            {"xht", "application/xhtml+xml"},\n            {"xhtml", "application/xhtml+xml"},\n            {"xls", "application/vnd.ms-excel"},\n            {"xml", "application/xml"},\n            {"xpm", "image/x-xpixmap"},\n            {"xsl", "application/xml"},\n            {"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},\n            {"xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},\n            {"xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},\n            {"xltm", "application/vnd.ms-excel.template.macroEnabled.12"},\n            {"xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},\n            {"xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},\n            {"xslt", "application/xslt+xml"},\n            {"xul", "application/vnd.mozilla.xul+xml"},\n            {"xwd", "image/x-xwindowdump"},\n            {"xyz", "chemical/x-xyz"},\n            {"zip", "application/zip"}\n        };\n}\n</code></pre>\n'}, {'answer_id': 22475295, 'author': 'tie', 'author_id': 922741, 'author_profile': 'https://Stackoverflow.com/users/922741', 'pm_score': 2, 'selected': False, 'text': '<p>This answer is a copy of the author\'s answer (Richard Gourlay), but improved to solve issues on IIS 8 / win2012 (where function would cause app pool to crash), based on Rohland\'s comment pointing to <a href="http://www.pinvoke.net/default.aspx/urlmon.findmimefromdata" rel="nofollow">http://www.pinvoke.net/default.aspx/urlmon.findmimefromdata</a></p>\n\n<pre><code>using System.Runtime.InteropServices;\n</code></pre>\n\n<p>...</p>\n\n<pre><code>public static string GetMimeFromFile(string filename)\n{\n\n    if (!File.Exists(filename))\n        throw new FileNotFoundException(filename + " not found");\n\n    const int maxContent = 256;\n\n    var buffer = new byte[maxContent];\n    using (var fs = new FileStream(filename, FileMode.Open))\n    {\n        if (fs.Length &gt;= maxContent)\n            fs.Read(buffer, 0, maxContent);\n        else\n            fs.Read(buffer, 0, (int) fs.Length);\n    }\n\n    var mimeTypePtr = IntPtr.Zero;\n    try\n    {\n        var result = FindMimeFromData(IntPtr.Zero, null, buffer, maxContent, null, 0, out mimeTypePtr, 0);\n        if (result != 0)\n        {\n            Marshal.FreeCoTaskMem(mimeTypePtr);\n            throw Marshal.GetExceptionForHR(result);\n        }\n\n        var mime = Marshal.PtrToStringUni(mimeTypePtr);\n        Marshal.FreeCoTaskMem(mimeTypePtr);\n        return mime;\n    }\n    catch (Exception e)\n    {\n        if (mimeTypePtr != IntPtr.Zero)\n        {\n            Marshal.FreeCoTaskMem(mimeTypePtr);\n        }\n        return "unknown/unknown";\n    }\n}\n\n[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]\nprivate static extern int FindMimeFromData(IntPtr pBC,\n    [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,\n    [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,\n    int cbSize,\n    [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,\n    int dwMimeFlags,\n    out IntPtr ppwzMimeOut,\n    int dwReserved);\n</code></pre>\n'}, {'answer_id': 24089256, 'author': 'cookch10msu', 'author_id': 1112224, 'author_profile': 'https://Stackoverflow.com/users/1112224', 'pm_score': 2, 'selected': False, 'text': '<p>@Steve Morgan and @Richard Gourlay this is a great solution, thank you for that.  One small drawback is that when the number of bytes in a file is 255 or below, the mime type will sometimes yield "application/octet-stream", which is slightly inaccurate for files which would be expected to yield "text/plain".  I have updated your original method to account for this situation as follows:</p>\n\n<p>If the number of bytes in the file is less than or equal to 255 and the deduced mime type is "application/octet-stream", then create a new byte array that consists of the original file bytes repeated n-times until the total number of bytes is >= 256.  Then re-check the mime-type on that new byte array.</p>\n\n<p>Modified method:</p>\n\n<pre><code>Imports System.Runtime.InteropServices\n\n&lt;DllImport("urlmon.dll", CharSet:=CharSet.Auto)&gt; _\nPrivate Shared Function FindMimeFromData(pBC As System.UInt32, &lt;MarshalAs(UnmanagedType.LPStr)&gt; pwzUrl As System.String, &lt;MarshalAs(UnmanagedType.LPArray)&gt; pBuffer As Byte(), cbSize As System.UInt32, &lt;MarshalAs(UnmanagedType.LPStr)&gt; pwzMimeProposed As System.String, dwMimeFlags As System.UInt32, _\nByRef ppwzMimeOut As System.UInt32, dwReserverd As System.UInt32) As System.UInt32\nEnd Function\nPrivate Function GetMimeType(ByVal f As FileInfo) As String\n    \'See http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature\n    Dim returnValue As String = ""\n    Dim fileStream As FileStream = Nothing\n    Dim fileStreamLength As Long = 0\n    Dim fileStreamIsLessThanBByteSize As Boolean = False\n\n    Const byteSize As Integer = 255\n    Const bbyteSize As Integer = byteSize + 1\n\n    Const ambiguousMimeType As String = "application/octet-stream"\n    Const unknownMimeType As String = "unknown/unknown"\n\n    Dim buffer As Byte() = New Byte(byteSize) {}\n    Dim fnGetMimeTypeValue As New Func(Of Byte(), Integer, String)(\n        Function(_buffer As Byte(), _bbyteSize As Integer) As String\n            Dim _returnValue As String = ""\n            Dim mimeType As UInt32 = 0\n            FindMimeFromData(0, Nothing, _buffer, _bbyteSize, Nothing, 0, mimeType, 0)\n            Dim mimeTypePtr As IntPtr = New IntPtr(mimeType)\n            _returnValue = Marshal.PtrToStringUni(mimeTypePtr)\n            Marshal.FreeCoTaskMem(mimeTypePtr)\n            Return _returnValue\n        End Function)\n\n    If (f.Exists()) Then\n        Try\n            fileStream = New FileStream(f.FullName(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)\n            fileStreamLength = fileStream.Length()\n\n            If (fileStreamLength &gt;= bbyteSize) Then\n                fileStream.Read(buffer, 0, bbyteSize)\n            Else\n                fileStreamIsLessThanBByteSize = True\n                fileStream.Read(buffer, 0, CInt(fileStreamLength))\n            End If\n\n            returnValue = fnGetMimeTypeValue(buffer, bbyteSize)\n\n            If (returnValue.Equals(ambiguousMimeType, StringComparison.OrdinalIgnoreCase) AndAlso fileStreamIsLessThanBByteSize AndAlso fileStreamLength &gt; 0) Then\n                \'Duplicate the stream content until the stream length is &gt;= bbyteSize to get a more deterministic mime type analysis.\n                Dim currentBuffer As Byte() = buffer.Take(fileStreamLength).ToArray()\n                Dim repeatCount As Integer = Math.Floor((bbyteSize / fileStreamLength) + 1)\n                Dim bBufferList As List(Of Byte) = New List(Of Byte)\n                While (repeatCount &gt; 0)\n                    bBufferList.AddRange(currentBuffer)\n                    repeatCount -= 1\n                End While\n                Dim bbuffer As Byte() = bBufferList.Take(bbyteSize).ToArray()\n                returnValue = fnGetMimeTypeValue(bbuffer, bbyteSize)\n            End If\n        Catch ex As Exception\n            returnValue = unknownMimeType\n        Finally\n            If (fileStream IsNot Nothing) Then fileStream.Close()\n        End Try\n    End If\n    Return returnValue\nEnd Function\n</code></pre>\n'}, {'answer_id': 45365396, 'author': 'maechler', 'author_id': 4494425, 'author_profile': 'https://Stackoverflow.com/users/4494425', 'pm_score': 0, 'selected': False, 'text': '<p>I ended up using Winista MimeDetector from Netomatix. The sources can be downloaded for free after you created an account: <a href="http://www.netomatix.com/Products/DocumentManagement/MimeDetector.aspx" rel="nofollow noreferrer">http://www.netomatix.com/Products/DocumentManagement/MimeDetector.aspx</a></p>\n\n<pre><code>MimeTypes g_MimeTypes = new MimeTypes("mime-types.xml");\nsbyte [] fileData = null;\n\nusing (System.IO.FileStream srcFile = new System.IO.FileStream(strFile, System.IO.FileMode.Open))\n{\n    byte [] data = new byte[srcFile.Length];\n    srcFile.Read(data, 0, (Int32)srcFile.Length);\n    fileData = Winista.Mime.SupportUtil.ToSByteArray(data);\n}\n\nMimeType oMimeType = g_MimeTypes.GetMimeType(fileData);\n</code></pre>\n\n<p>This is part of another question answered here: <a href="https://stackoverflow.com/questions/15300567/alternative-to-findmimefromdata-method-in-urlmon-dll-one-which-has-more-mime-typ/15595571#15595571">Alternative to FindMimeFromData method in Urlmon.dll one which has more MIME types</a>\nThe best solution to this problem in my opinion.</p>\n'}, {'answer_id': 59190598, 'author': 'Ivan Kirichuk', 'author_id': 9336690, 'author_profile': 'https://Stackoverflow.com/users/9336690', 'pm_score': 0, 'selected': False, 'text': '<p>I found several problems of running this code:</p>\n\n<pre><code>UInt32 mimetype;\nFindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);\n</code></pre>\n\n<p>If you will try to run it with x64/Win10 you will get</p>\n\n<pre><code>AccessViolationException "Attempted to read or write protected memory.\nThis is often an indication that other memory is corrupt"\n</code></pre>\n\n<p>Thanks to this post <a href="https://stackoverflow.com/questions/51037460/ptrtostringuni-doesnt-work-in-windows-10">PtrToStringUni doesnt work in windows 10</a> and @xanatos</p>\n\n<p>I modified my solution to run under x64 and .NET Core 2.1:</p>\n\n<pre><code>   [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, \n    SetLastError = false)]\n    static extern int FindMimeFromData(IntPtr pBC,\n        [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,\n        [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, \n        SizeParamIndex=3)]\n        byte[] pBuffer,\n        int cbSize,\n        [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,\n        int dwMimeFlags,\n        out IntPtr ppwzMimeOut,\n        int dwReserved);\n\n   string getMimeFromFile(byte[] fileSource)\n   {\n            byte[] buffer = new byte[256];\n            using (Stream stream = new MemoryStream(fileSource))\n            {\n                if (stream.Length &gt;= 256)\n                    stream.Read(buffer, 0, 256);\n                else\n                    stream.Read(buffer, 0, (int)stream.Length);\n            }\n\n            try\n            {\n                IntPtr mimeTypePtr;\n                FindMimeFromData(IntPtr.Zero, null, buffer, buffer.Length,\n                    null, 0, out mimeTypePtr, 0);\n\n                string mime = Marshal.PtrToStringUni(mimeTypePtr);\n                Marshal.FreeCoTaskMem(mimeTypePtr);\n                return mime;\n            }\n            catch (Exception ex)\n            {\n                return "unknown/unknown";\n            }\n   }\n</code></pre>\n\n<p>Thanks</p>\n'}, {'answer_id': 59371020, 'author': 'GetoX', 'author_id': 4477336, 'author_profile': 'https://Stackoverflow.com/users/4477336', 'pm_score': 0, 'selected': False, 'text': '<p>Hello I have adapted Winista.MimeDetect project into .net core/framework with fallback into urlmon.dll Fell free to use it: <a href="https://www.nuget.org/packages/Winista.MimeDetect" rel="nofollow noreferrer">nuget package</a>. </p>\n\n<pre><code>   //init\n   var mimeTypes = new MimeTypes();\n\n   //usage by filepath\n   var mimeType1 = mimeTypes.GetMimeTypeFromFile(filePath);\n</code></pre>\n'}, {'answer_id': 60026738, 'author': 'Egbert Nierop', 'author_id': 2410689, 'author_profile': 'https://Stackoverflow.com/users/2410689', 'pm_score': 4, 'selected': False, 'text': '<p><code>HeyRed.Mime.MimeGuesser.GuessMimeType</code> from Nuget would be the ultimate solution if you want to host your ASP.NET solution on non-windows environments.</p>\n\n<p>File extension mapping is very insecure. If an attacker would upload invalid extensions, a mapping dictionary would e.g. allow executables to be distributed inside .jpg files.\nTherefore, always use a content-sniffing library to know the real content-type.</p>\n\n<pre><code> public  static string MimeTypeFrom(byte[] dataBytes, string fileName)\n {\n        var contentType = HeyRed.Mime.MimeGuesser.GuessMimeType(dataBytes);\n        if (string.IsNullOrEmpty(contentType))\n        {\n            return HeyRed.Mime.MimeTypesMap.GetMimeType(fileName);\n        }\n  return contentType;\n</code></pre>\n'}, {'answer_id': 61893701, 'author': 'Artem Beziazychnyi', 'author_id': 9349612, 'author_profile': 'https://Stackoverflow.com/users/9349612', 'pm_score': 3, 'selected': False, 'text': '<p>I wrote a validator of mime type. Kindly share it with you.</p>\n\n<pre><code>private readonly Dictionary&lt;string, byte[]&gt; _mimeTypes = new Dictionary&lt;string, byte[]&gt;\n    {\n        {"image/jpeg", new byte[] {255, 216, 255}},\n        {"image/jpg", new byte[] {255, 216, 255}},\n        {"image/pjpeg", new byte[] {255, 216, 255}},\n        {"image/apng", new byte[] {137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82}},\n        {"image/png", new byte[] {137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82}},\n        {"image/bmp", new byte[] {66, 77}},\n        {"image/gif", new byte[] {71, 73, 70, 56}},\n    };\n\nprivate bool ValidateMimeType(byte[] file, string contentType)\n    {\n        var imageType = _mimeTypes.SingleOrDefault(x =&gt; x.Key.Equals(contentType));\n\n        return file.Take(imageType.Value.Length).SequenceEqual(imageType.Value);\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/58510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2674/']