Ruft den MIME-Typ von der Dateinamenerweiterung ab


349

Wie kann ich den MIME-Typ aus einer Dateierweiterung abrufen?



2
@ Yuki, danke für das Hinzufügen neuer relevanter Informationen. Leider verfügt die MS-Implementierung, die in .NET 4.5 verfügbar ist, nur über 195 Zuordnungen, kann keine weiteren hinzufügen und ist nicht konfigurierbar. Mein Eintrag unten hat mehr als 560 Zuordnungen. Seltsamerweise fehlen in der MS-Liste sogar extrem häufige MS-Erweiterungen wie .docx und .xlsx sowie andere wichtige Web-Erweiterungen wie .csv, .swf und .air.
Samuel Neff

Antworten:


435

Für ASP.NET oder andere

Die Optionen wurden in ASP.NET Core ein wenig geändert, hier sind sie ( Credits ):

  • new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType); (nur vNext)
    • Nie getestet, aber es sieht so aus, als könnten Sie die Liste der MIME-Typen offiziell über die exponierte MappingsEigenschaft erweitern.
  • Verwenden Sie das MimeTypesNuGet-Paket
  • Kopieren Sie die MimeMappingsDatei aus der Referenzquelle von .NET Framework

Für .NET Framework> = 4.5:

Verwenden Sie die System.Web.MimeMapping.GetMimeMappingMethode, die Teil der BCL in .NET Framework 4.5 ist:

string mimeType = MimeMapping.GetMimeMapping(fileName);

Wenn Sie benutzerdefinierte Zuordnungen hinzufügen müssen, können Sie wahrscheinlich Reflection verwenden, um der BCL- MimeMappingKlasse Zuordnungen hinzuzufügen. Es wird ein benutzerdefiniertes Wörterbuch verwendet, das diese Methode verfügbar macht. Sie sollten daher Folgendes aufrufen, um Zuordnungen hinzuzufügen (nie getestet, sollte aber funktionieren). .

Wenn Sie Reflection zum Hinzufügen von MIME-Typen verwenden, beachten Sie, dass sich der Name des Zugriffs auf ein privates Feld möglicherweise ändert oder sogar vollständig entfernt wird. Sie sollten daher besonders vorsichtig sein und doppelte Überprüfungen hinzufügen und für jeden Schritt eine ausfallsichere Aktion bereitstellen .

MimeMapping._mappingDictionary.AddMapping(string fileExtension, string mimeType)

18
+1 für das Hinzufügen neuer relevanter Informationen. Leider verfügt die in .NET 4.5 verfügbare MS-Implementierung nur über 195 Zuordnungen, kann keine weiteren hinzufügen und ist nicht konfigurierbar. Mein Eintrag oben hat 560 Zuordnungen. Merkwürdig ist , dass die Auflistung der MS fehlt sehr häufig MS - Erweiterungen auch, wie .docxund .xlsxund andere wichtige Web - Erweiterungen wie .csv, .swf, und .air.
Samuel Neff

@SamuelNeff Sie können Zuordnungen natürlich mit Reflection ( MimeMapping._mappingDictionary.AddMapping(string fileExtension, string mimeType)) hinzufügen .
Shimmy Weitzhandler

20
Es ist keine gute Idee, über private Felder nachzudenken. Es ist wahrscheinlicher, dass sie sich in Zukunft ändern, da es sich nicht um einen vereinbarten Vertrag handelt und Sie in diesem Fall einen Laufzeitfehler anstelle eines Kompilierungsfehlers erhalten. Wenn Sie dies tun, sollten Sie mindestens Komponententests hinzufügen, um sicherzustellen, dass diese beim Aktualisieren von .NET-Versionen frühzeitig erkannt werden. Wenn Sie Zuordnungen manuell hinzufügen möchten, können Sie außerdem Ihre eigene Sammlung verwalten. Die Klasse ist nichts weiter als ein Wrapper in einem Wörterbuch.
Samuel Neff

10
Das verhindert zwar Fehler, aber wenn die Variablen und Methoden nicht vorhanden sind, funktioniert Ihr Code zum Hinzufügen benutzerdefinierter Zuordnungen nicht. Sie werden einfach keine Fehler mehr bekommen. Wir können nicht zustimmen und argumentieren, unter dem Strich haben Sie Recht, Sie können es technisch durch Reflexion nennen, aber ich persönlich würde niemals empfehlen, Reflexion über private Immobilien in einer Produktionsanwendung zu verwenden, es sei denn, dies war absolut notwendig und ohne angemessene Sicherheitsvorkehrungen, um es frühzeitig zu erkennen, wenn es schlägt fehl.
Samuel Neff

8
FWIW, System.Web wurde aus ASP.NET CORE (asp.net 5) entfernt, was bedeutet, dass kein MimeMapping mehr erforderlich ist.
Nick De Beer

403

AKTUALISIEREN

Aktuelle Zuordnungen mit Ergänzungen von vielen Mitwirkenden finden Sie in diesem GitHub-Repository:

https://github.com/samuelneff/MimeTypeMap


Ich habe festgestellt, dass viele MIME-Typen, die meine Anwendung verwendet, nicht in der Standard-Windows-Registrierung enthalten sind und andere in der Registrierung, jedoch nicht in der in IIS enthaltenen Liste. Ich habe eine Liste von diesen Orten zusammengestellt und einige andere hinzugefügt, die wir verwenden.

EDIT: Siehe meisten up-do-date - Version mit Beiträgen hier , einschließlich einer effizienten und deterministische Zwei-Wege - Mapping.

private static IDictionary<string, string> _mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {

        #region Big freaking list of mime types
        // combination of values from Windows 7 Registry and 
        // from C:\Windows\System32\inetsrv\config\applicationHost.config
        // some added, including .7z and .dat
        {".323", "text/h323"},
        {".3g2", "video/3gpp2"},
        {".3gp", "video/3gpp"},
        {".3gp2", "video/3gpp2"},
        {".3gpp", "video/3gpp"},
        {".7z", "application/x-7z-compressed"},
        {".aa", "audio/audible"},
        {".AAC", "audio/aac"},
        {".aaf", "application/octet-stream"},
        {".aax", "audio/vnd.audible.aax"},
        {".ac3", "audio/ac3"},
        {".aca", "application/octet-stream"},
        {".accda", "application/msaccess.addin"},
        {".accdb", "application/msaccess"},
        {".accdc", "application/msaccess.cab"},
        {".accde", "application/msaccess"},
        {".accdr", "application/msaccess.runtime"},
        {".accdt", "application/msaccess"},
        {".accdw", "application/msaccess.webapplication"},
        {".accft", "application/msaccess.ftemplate"},
        {".acx", "application/internet-property-stream"},
        {".AddIn", "text/xml"},
        {".ade", "application/msaccess"},
        {".adobebridge", "application/x-bridge-url"},
        {".adp", "application/msaccess"},
        {".ADT", "audio/vnd.dlna.adts"},
        {".ADTS", "audio/aac"},
        {".afm", "application/octet-stream"},
        {".ai", "application/postscript"},
        {".aif", "audio/x-aiff"},
        {".aifc", "audio/aiff"},
        {".aiff", "audio/aiff"},
        {".air", "application/vnd.adobe.air-application-installer-package+zip"},
        {".amc", "application/x-mpeg"},
        {".application", "application/x-ms-application"},
        {".art", "image/x-jg"},
        {".asa", "application/xml"},
        {".asax", "application/xml"},
        {".ascx", "application/xml"},
        {".asd", "application/octet-stream"},
        {".asf", "video/x-ms-asf"},
        {".ashx", "application/xml"},
        {".asi", "application/octet-stream"},
        {".asm", "text/plain"},
        {".asmx", "application/xml"},
        {".aspx", "application/xml"},
        {".asr", "video/x-ms-asf"},
        {".asx", "video/x-ms-asf"},
        {".atom", "application/atom+xml"},
        {".au", "audio/basic"},
        {".avi", "video/x-msvideo"},
        {".axs", "application/olescript"},
        {".bas", "text/plain"},
        {".bcpio", "application/x-bcpio"},
        {".bin", "application/octet-stream"},
        {".bmp", "image/bmp"},
        {".c", "text/plain"},
        {".cab", "application/octet-stream"},
        {".caf", "audio/x-caf"},
        {".calx", "application/vnd.ms-office.calx"},
        {".cat", "application/vnd.ms-pki.seccat"},
        {".cc", "text/plain"},
        {".cd", "text/plain"},
        {".cdda", "audio/aiff"},
        {".cdf", "application/x-cdf"},
        {".cer", "application/x-x509-ca-cert"},
        {".chm", "application/octet-stream"},
        {".class", "application/x-java-applet"},
        {".clp", "application/x-msclip"},
        {".cmx", "image/x-cmx"},
        {".cnf", "text/plain"},
        {".cod", "image/cis-cod"},
        {".config", "application/xml"},
        {".contact", "text/x-ms-contact"},
        {".coverage", "application/xml"},
        {".cpio", "application/x-cpio"},
        {".cpp", "text/plain"},
        {".crd", "application/x-mscardfile"},
        {".crl", "application/pkix-crl"},
        {".crt", "application/x-x509-ca-cert"},
        {".cs", "text/plain"},
        {".csdproj", "text/plain"},
        {".csh", "application/x-csh"},
        {".csproj", "text/plain"},
        {".css", "text/css"},
        {".csv", "text/csv"},
        {".cur", "application/octet-stream"},
        {".cxx", "text/plain"},
        {".dat", "application/octet-stream"},
        {".datasource", "application/xml"},
        {".dbproj", "text/plain"},
        {".dcr", "application/x-director"},
        {".def", "text/plain"},
        {".deploy", "application/octet-stream"},
        {".der", "application/x-x509-ca-cert"},
        {".dgml", "application/xml"},
        {".dib", "image/bmp"},
        {".dif", "video/x-dv"},
        {".dir", "application/x-director"},
        {".disco", "text/xml"},
        {".dll", "application/x-msdownload"},
        {".dll.config", "text/xml"},
        {".dlm", "text/dlm"},
        {".doc", "application/msword"},
        {".docm", "application/vnd.ms-word.document.macroEnabled.12"},
        {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
        {".dot", "application/msword"},
        {".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
        {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
        {".dsp", "application/octet-stream"},
        {".dsw", "text/plain"},
        {".dtd", "text/xml"},
        {".dtsConfig", "text/xml"},
        {".dv", "video/x-dv"},
        {".dvi", "application/x-dvi"},
        {".dwf", "drawing/x-dwf"},
        {".dwp", "application/octet-stream"},
        {".dxr", "application/x-director"},
        {".eml", "message/rfc822"},
        {".emz", "application/octet-stream"},
        {".eot", "application/octet-stream"},
        {".eps", "application/postscript"},
        {".etl", "application/etl"},
        {".etx", "text/x-setext"},
        {".evy", "application/envoy"},
        {".exe", "application/octet-stream"},
        {".exe.config", "text/xml"},
        {".fdf", "application/vnd.fdf"},
        {".fif", "application/fractals"},
        {".filters", "Application/xml"},
        {".fla", "application/octet-stream"},
        {".flr", "x-world/x-vrml"},
        {".flv", "video/x-flv"},
        {".fsscript", "application/fsharp-script"},
        {".fsx", "application/fsharp-script"},
        {".generictest", "application/xml"},
        {".gif", "image/gif"},
        {".group", "text/x-ms-group"},
        {".gsm", "audio/x-gsm"},
        {".gtar", "application/x-gtar"},
        {".gz", "application/x-gzip"},
        {".h", "text/plain"},
        {".hdf", "application/x-hdf"},
        {".hdml", "text/x-hdml"},
        {".hhc", "application/x-oleobject"},
        {".hhk", "application/octet-stream"},
        {".hhp", "application/octet-stream"},
        {".hlp", "application/winhlp"},
        {".hpp", "text/plain"},
        {".hqx", "application/mac-binhex40"},
        {".hta", "application/hta"},
        {".htc", "text/x-component"},
        {".htm", "text/html"},
        {".html", "text/html"},
        {".htt", "text/webviewhtml"},
        {".hxa", "application/xml"},
        {".hxc", "application/xml"},
        {".hxd", "application/octet-stream"},
        {".hxe", "application/xml"},
        {".hxf", "application/xml"},
        {".hxh", "application/octet-stream"},
        {".hxi", "application/octet-stream"},
        {".hxk", "application/xml"},
        {".hxq", "application/octet-stream"},
        {".hxr", "application/octet-stream"},
        {".hxs", "application/octet-stream"},
        {".hxt", "text/html"},
        {".hxv", "application/xml"},
        {".hxw", "application/octet-stream"},
        {".hxx", "text/plain"},
        {".i", "text/plain"},
        {".ico", "image/x-icon"},
        {".ics", "application/octet-stream"},
        {".idl", "text/plain"},
        {".ief", "image/ief"},
        {".iii", "application/x-iphone"},
        {".inc", "text/plain"},
        {".inf", "application/octet-stream"},
        {".inl", "text/plain"},
        {".ins", "application/x-internet-signup"},
        {".ipa", "application/x-itunes-ipa"},
        {".ipg", "application/x-itunes-ipg"},
        {".ipproj", "text/plain"},
        {".ipsw", "application/x-itunes-ipsw"},
        {".iqy", "text/x-ms-iqy"},
        {".isp", "application/x-internet-signup"},
        {".ite", "application/x-itunes-ite"},
        {".itlp", "application/x-itunes-itlp"},
        {".itms", "application/x-itunes-itms"},
        {".itpc", "application/x-itunes-itpc"},
        {".IVF", "video/x-ivf"},
        {".jar", "application/java-archive"},
        {".java", "application/octet-stream"},
        {".jck", "application/liquidmotion"},
        {".jcz", "application/liquidmotion"},
        {".jfif", "image/pjpeg"},
        {".jnlp", "application/x-java-jnlp-file"},
        {".jpb", "application/octet-stream"},
        {".jpe", "image/jpeg"},
        {".jpeg", "image/jpeg"},
        {".jpg", "image/jpeg"},
        {".js", "application/x-javascript"},
        {".json", "application/json"},
        {".jsx", "text/jscript"},
        {".jsxbin", "text/plain"},
        {".latex", "application/x-latex"},
        {".library-ms", "application/windows-library+xml"},
        {".lit", "application/x-ms-reader"},
        {".loadtest", "application/xml"},
        {".lpk", "application/octet-stream"},
        {".lsf", "video/x-la-asf"},
        {".lst", "text/plain"},
        {".lsx", "video/x-la-asf"},
        {".lzh", "application/octet-stream"},
        {".m13", "application/x-msmediaview"},
        {".m14", "application/x-msmediaview"},
        {".m1v", "video/mpeg"},
        {".m2t", "video/vnd.dlna.mpeg-tts"},
        {".m2ts", "video/vnd.dlna.mpeg-tts"},
        {".m2v", "video/mpeg"},
        {".m3u", "audio/x-mpegurl"},
        {".m3u8", "audio/x-mpegurl"},
        {".m4a", "audio/m4a"},
        {".m4b", "audio/m4b"},
        {".m4p", "audio/m4p"},
        {".m4r", "audio/x-m4r"},
        {".m4v", "video/x-m4v"},
        {".mac", "image/x-macpaint"},
        {".mak", "text/plain"},
        {".man", "application/x-troff-man"},
        {".manifest", "application/x-ms-manifest"},
        {".map", "text/plain"},
        {".master", "application/xml"},
        {".mda", "application/msaccess"},
        {".mdb", "application/x-msaccess"},
        {".mde", "application/msaccess"},
        {".mdp", "application/octet-stream"},
        {".me", "application/x-troff-me"},
        {".mfp", "application/x-shockwave-flash"},
        {".mht", "message/rfc822"},
        {".mhtml", "message/rfc822"},
        {".mid", "audio/mid"},
        {".midi", "audio/mid"},
        {".mix", "application/octet-stream"},
        {".mk", "text/plain"},
        {".mmf", "application/x-smaf"},
        {".mno", "text/xml"},
        {".mny", "application/x-msmoney"},
        {".mod", "video/mpeg"},
        {".mov", "video/quicktime"},
        {".movie", "video/x-sgi-movie"},
        {".mp2", "video/mpeg"},
        {".mp2v", "video/mpeg"},
        {".mp3", "audio/mpeg"},
        {".mp4", "video/mp4"},
        {".mp4v", "video/mp4"},
        {".mpa", "video/mpeg"},
        {".mpe", "video/mpeg"},
        {".mpeg", "video/mpeg"},
        {".mpf", "application/vnd.ms-mediapackage"},
        {".mpg", "video/mpeg"},
        {".mpp", "application/vnd.ms-project"},
        {".mpv2", "video/mpeg"},
        {".mqv", "video/quicktime"},
        {".ms", "application/x-troff-ms"},
        {".msi", "application/octet-stream"},
        {".mso", "application/octet-stream"},
        {".mts", "video/vnd.dlna.mpeg-tts"},
        {".mtx", "application/xml"},
        {".mvb", "application/x-msmediaview"},
        {".mvc", "application/x-miva-compiled"},
        {".mxp", "application/x-mmxp"},
        {".nc", "application/x-netcdf"},
        {".nsc", "video/x-ms-asf"},
        {".nws", "message/rfc822"},
        {".ocx", "application/octet-stream"},
        {".oda", "application/oda"},
        {".odc", "text/x-ms-odc"},
        {".odh", "text/plain"},
        {".odl", "text/plain"},
        {".odp", "application/vnd.oasis.opendocument.presentation"},
        {".ods", "application/oleobject"},
        {".odt", "application/vnd.oasis.opendocument.text"},
        {".one", "application/onenote"},
        {".onea", "application/onenote"},
        {".onepkg", "application/onenote"},
        {".onetmp", "application/onenote"},
        {".onetoc", "application/onenote"},
        {".onetoc2", "application/onenote"},
        {".orderedtest", "application/xml"},
        {".osdx", "application/opensearchdescription+xml"},
        {".p10", "application/pkcs10"},
        {".p12", "application/x-pkcs12"},
        {".p7b", "application/x-pkcs7-certificates"},
        {".p7c", "application/pkcs7-mime"},
        {".p7m", "application/pkcs7-mime"},
        {".p7r", "application/x-pkcs7-certreqresp"},
        {".p7s", "application/pkcs7-signature"},
        {".pbm", "image/x-portable-bitmap"},
        {".pcast", "application/x-podcast"},
        {".pct", "image/pict"},
        {".pcx", "application/octet-stream"},
        {".pcz", "application/octet-stream"},
        {".pdf", "application/pdf"},
        {".pfb", "application/octet-stream"},
        {".pfm", "application/octet-stream"},
        {".pfx", "application/x-pkcs12"},
        {".pgm", "image/x-portable-graymap"},
        {".pic", "image/pict"},
        {".pict", "image/pict"},
        {".pkgdef", "text/plain"},
        {".pkgundef", "text/plain"},
        {".pko", "application/vnd.ms-pki.pko"},
        {".pls", "audio/scpls"},
        {".pma", "application/x-perfmon"},
        {".pmc", "application/x-perfmon"},
        {".pml", "application/x-perfmon"},
        {".pmr", "application/x-perfmon"},
        {".pmw", "application/x-perfmon"},
        {".png", "image/png"},
        {".pnm", "image/x-portable-anymap"},
        {".pnt", "image/x-macpaint"},
        {".pntg", "image/x-macpaint"},
        {".pnz", "image/png"},
        {".pot", "application/vnd.ms-powerpoint"},
        {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
        {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
        {".ppa", "application/vnd.ms-powerpoint"},
        {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
        {".ppm", "image/x-portable-pixmap"},
        {".pps", "application/vnd.ms-powerpoint"},
        {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
        {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
        {".ppt", "application/vnd.ms-powerpoint"},
        {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
        {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
        {".prf", "application/pics-rules"},
        {".prm", "application/octet-stream"},
        {".prx", "application/octet-stream"},
        {".ps", "application/postscript"},
        {".psc1", "application/PowerShell"},
        {".psd", "application/octet-stream"},
        {".psess", "application/xml"},
        {".psm", "application/octet-stream"},
        {".psp", "application/octet-stream"},
        {".pub", "application/x-mspublisher"},
        {".pwz", "application/vnd.ms-powerpoint"},
        {".qht", "text/x-html-insertion"},
        {".qhtm", "text/x-html-insertion"},
        {".qt", "video/quicktime"},
        {".qti", "image/x-quicktime"},
        {".qtif", "image/x-quicktime"},
        {".qtl", "application/x-quicktimeplayer"},
        {".qxd", "application/octet-stream"},
        {".ra", "audio/x-pn-realaudio"},
        {".ram", "audio/x-pn-realaudio"},
        {".rar", "application/octet-stream"},
        {".ras", "image/x-cmu-raster"},
        {".rat", "application/rat-file"},
        {".rc", "text/plain"},
        {".rc2", "text/plain"},
        {".rct", "text/plain"},
        {".rdlc", "application/xml"},
        {".resx", "application/xml"},
        {".rf", "image/vnd.rn-realflash"},
        {".rgb", "image/x-rgb"},
        {".rgs", "text/plain"},
        {".rm", "application/vnd.rn-realmedia"},
        {".rmi", "audio/mid"},
        {".rmp", "application/vnd.rn-rn_music_package"},
        {".roff", "application/x-troff"},
        {".rpm", "audio/x-pn-realaudio-plugin"},
        {".rqy", "text/x-ms-rqy"},
        {".rtf", "application/rtf"},
        {".rtx", "text/richtext"},
        {".ruleset", "application/xml"},
        {".s", "text/plain"},
        {".safariextz", "application/x-safari-safariextz"},
        {".scd", "application/x-msschedule"},
        {".sct", "text/scriptlet"},
        {".sd2", "audio/x-sd2"},
        {".sdp", "application/sdp"},
        {".sea", "application/octet-stream"},
        {".searchConnector-ms", "application/windows-search-connector+xml"},
        {".setpay", "application/set-payment-initiation"},
        {".setreg", "application/set-registration-initiation"},
        {".settings", "application/xml"},
        {".sgimb", "application/x-sgimb"},
        {".sgml", "text/sgml"},
        {".sh", "application/x-sh"},
        {".shar", "application/x-shar"},
        {".shtml", "text/html"},
        {".sit", "application/x-stuffit"},
        {".sitemap", "application/xml"},
        {".skin", "application/xml"},
        {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
        {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
        {".slk", "application/vnd.ms-excel"},
        {".sln", "text/plain"},
        {".slupkg-ms", "application/x-ms-license"},
        {".smd", "audio/x-smd"},
        {".smi", "application/octet-stream"},
        {".smx", "audio/x-smd"},
        {".smz", "audio/x-smd"},
        {".snd", "audio/basic"},
        {".snippet", "application/xml"},
        {".snp", "application/octet-stream"},
        {".sol", "text/plain"},
        {".sor", "text/plain"},
        {".spc", "application/x-pkcs7-certificates"},
        {".spl", "application/futuresplash"},
        {".src", "application/x-wais-source"},
        {".srf", "text/plain"},
        {".SSISDeploymentManifest", "text/xml"},
        {".ssm", "application/streamingmedia"},
        {".sst", "application/vnd.ms-pki.certstore"},
        {".stl", "application/vnd.ms-pki.stl"},
        {".sv4cpio", "application/x-sv4cpio"},
        {".sv4crc", "application/x-sv4crc"},
        {".svc", "application/xml"},
        {".swf", "application/x-shockwave-flash"},
        {".t", "application/x-troff"},
        {".tar", "application/x-tar"},
        {".tcl", "application/x-tcl"},
        {".testrunconfig", "application/xml"},
        {".testsettings", "application/xml"},
        {".tex", "application/x-tex"},
        {".texi", "application/x-texinfo"},
        {".texinfo", "application/x-texinfo"},
        {".tgz", "application/x-compressed"},
        {".thmx", "application/vnd.ms-officetheme"},
        {".thn", "application/octet-stream"},
        {".tif", "image/tiff"},
        {".tiff", "image/tiff"},
        {".tlh", "text/plain"},
        {".tli", "text/plain"},
        {".toc", "application/octet-stream"},
        {".tr", "application/x-troff"},
        {".trm", "application/x-msterminal"},
        {".trx", "application/xml"},
        {".ts", "video/vnd.dlna.mpeg-tts"},
        {".tsv", "text/tab-separated-values"},
        {".ttf", "application/octet-stream"},
        {".tts", "video/vnd.dlna.mpeg-tts"},
        {".txt", "text/plain"},
        {".u32", "application/octet-stream"},
        {".uls", "text/iuls"},
        {".user", "text/plain"},
        {".ustar", "application/x-ustar"},
        {".vb", "text/plain"},
        {".vbdproj", "text/plain"},
        {".vbk", "video/mpeg"},
        {".vbproj", "text/plain"},
        {".vbs", "text/vbscript"},
        {".vcf", "text/x-vcard"},
        {".vcproj", "Application/xml"},
        {".vcs", "text/plain"},
        {".vcxproj", "Application/xml"},
        {".vddproj", "text/plain"},
        {".vdp", "text/plain"},
        {".vdproj", "text/plain"},
        {".vdx", "application/vnd.ms-visio.viewer"},
        {".vml", "text/xml"},
        {".vscontent", "application/xml"},
        {".vsct", "text/xml"},
        {".vsd", "application/vnd.visio"},
        {".vsi", "application/ms-vsi"},
        {".vsix", "application/vsix"},
        {".vsixlangpack", "text/xml"},
        {".vsixmanifest", "text/xml"},
        {".vsmdi", "application/xml"},
        {".vspscc", "text/plain"},
        {".vss", "application/vnd.visio"},
        {".vsscc", "text/plain"},
        {".vssettings", "text/xml"},
        {".vssscc", "text/plain"},
        {".vst", "application/vnd.visio"},
        {".vstemplate", "text/xml"},
        {".vsto", "application/x-ms-vsto"},
        {".vsw", "application/vnd.visio"},
        {".vsx", "application/vnd.visio"},
        {".vtx", "application/vnd.visio"},
        {".wav", "audio/wav"},
        {".wave", "audio/wav"},
        {".wax", "audio/x-ms-wax"},
        {".wbk", "application/msword"},
        {".wbmp", "image/vnd.wap.wbmp"},
        {".wcm", "application/vnd.ms-works"},
        {".wdb", "application/vnd.ms-works"},
        {".wdp", "image/vnd.ms-photo"},
        {".webarchive", "application/x-safari-webarchive"},
        {".webtest", "application/xml"},
        {".wiq", "application/xml"},
        {".wiz", "application/msword"},
        {".wks", "application/vnd.ms-works"},
        {".WLMP", "application/wlmoviemaker"},
        {".wlpginstall", "application/x-wlpg-detect"},
        {".wlpginstall3", "application/x-wlpg3-detect"},
        {".wm", "video/x-ms-wm"},
        {".wma", "audio/x-ms-wma"},
        {".wmd", "application/x-ms-wmd"},
        {".wmf", "application/x-msmetafile"},
        {".wml", "text/vnd.wap.wml"},
        {".wmlc", "application/vnd.wap.wmlc"},
        {".wmls", "text/vnd.wap.wmlscript"},
        {".wmlsc", "application/vnd.wap.wmlscriptc"},
        {".wmp", "video/x-ms-wmp"},
        {".wmv", "video/x-ms-wmv"},
        {".wmx", "video/x-ms-wmx"},
        {".wmz", "application/x-ms-wmz"},
        {".wpl", "application/vnd.ms-wpl"},
        {".wps", "application/vnd.ms-works"},
        {".wri", "application/x-mswrite"},
        {".wrl", "x-world/x-vrml"},
        {".wrz", "x-world/x-vrml"},
        {".wsc", "text/scriptlet"},
        {".wsdl", "text/xml"},
        {".wvx", "video/x-ms-wvx"},
        {".x", "application/directx"},
        {".xaf", "x-world/x-vrml"},
        {".xaml", "application/xaml+xml"},
        {".xap", "application/x-silverlight-app"},
        {".xbap", "application/x-ms-xbap"},
        {".xbm", "image/x-xbitmap"},
        {".xdr", "text/plain"},
        {".xht", "application/xhtml+xml"},
        {".xhtml", "application/xhtml+xml"},
        {".xla", "application/vnd.ms-excel"},
        {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
        {".xlc", "application/vnd.ms-excel"},
        {".xld", "application/vnd.ms-excel"},
        {".xlk", "application/vnd.ms-excel"},
        {".xll", "application/vnd.ms-excel"},
        {".xlm", "application/vnd.ms-excel"},
        {".xls", "application/vnd.ms-excel"},
        {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
        {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
        {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
        {".xlt", "application/vnd.ms-excel"},
        {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
        {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
        {".xlw", "application/vnd.ms-excel"},
        {".xml", "text/xml"},
        {".xmta", "application/xml"},
        {".xof", "x-world/x-vrml"},
        {".XOML", "text/plain"},
        {".xpm", "image/x-xpixmap"},
        {".xps", "application/vnd.ms-xpsdocument"},
        {".xrm-ms", "text/xml"},
        {".xsc", "application/xml"},
        {".xsd", "text/xml"},
        {".xsf", "text/xml"},
        {".xsl", "text/xml"},
        {".xslt", "text/xml"},
        {".xsn", "application/octet-stream"},
        {".xss", "application/xml"},
        {".xtp", "application/octet-stream"},
        {".xwd", "image/x-xwindowdump"},
        {".z", "application/x-compress"},
        {".zip", "application/x-zip-compressed"},
        #endregion

        };

public static string GetMimeType(string extension)
{
    if (extension == null)
    {
        throw new ArgumentNullException("extension");
    }

    if (!extension.StartsWith("."))
    {
        extension = "." + extension;
    }

    string mime;

    return _mappings.TryGetValue(extension, out mime) ? mime : "application/octet-stream";
}

28
Irgendwie habe ich das Gefühl, dass das Erstellen einer assoziativen Datenstruktur aus einer Datendatei beim Start etwas vernünftiger wäre.
Jon Purdy

13
Hey pplz MSFT hat es jetzt implementiert! Überprüfen Sie dies
Shimmy Weitzhandler

6
@ Shimmy, interessant. Leider verfügt die in .NET 4.5 verfügbare MS-Implementierung nur über 195 Zuordnungen, kann keine weiteren hinzufügen und ist nicht konfigurierbar. Mein Eintrag oben hat 560 Zuordnungen. Merkwürdig ist , dass die Auflistung der MS fehlt sehr häufig MS - Erweiterungen auch, wie .docxund .xlsxund andere wichtige Web - Erweiterungen wie .csv, .swf, und .air.
Samuel Neff

1
@ JonPurdy, ich bin endlich dazu gekommen, es umzugestalten, um ein Wörterbuch zu verwenden.
Samuel Neff

2
@AnthonyVO, lustig, ich hatte es ursprünglich als Schalter. Wenn Sie Zeichenfolgen zum Einschalten erstellen, ist der Aufwand höher als bei einem Wörterbuch. Dekompilieren Sie den Code. Was es tatsächlich tut, ist, dass es ein Wörterbuch mit Zeigern erstellt und dann den Zeiger im Wörterbuch nachschlägt, um zu dieser Position zu springen. Dictionary hat daher tatsächlich weniger Overhead.
Samuel Neff

52

Sie können diese Hilfsfunktion verwenden:

private string GetMimeType (string fileName)
{
    string mimeType = "application/unknown";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey != null && regKey.GetValue("Content Type") != null)
    mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}

18
Beachten Sie, dass der Computer, auf dem Sie diesen Code ausführen, nur einige Typen "kennt" - z. B. wird PDF nicht aufgelistet, wenn auf dem Computer noch nie ein PDF-Reader installiert war.
Msulis

Ja, dies ist etwas gefährlich, da es aus der Registrierung stammt und Erweiterungen von nicht installierter Software übersehen kann. Beispiel .xlsx, wenn nur alte Versionen von Office vorhanden sind, hat nur .xls
Nestor

2
Darüber hinaus wäre dies ein sehr teurer Aufruf, um jedes Mal, wenn Sie einen MIME-Typ benötigen, eine Registrierungssuche durchzuführen. Vielleicht, wenn es zwischengespeichert wäre, aber ich würde immer noch die statische Wörterbuchmethode von Samuel bevorzugen.
Mark

5
... oder wenn Sie Mono verwenden, steht Ihnen nicht wirklich eine Windows-Registrierung zur Verfügung ... :)
enorl76

@dadwithkids Ich bin mir nicht sicher, warum eine Registrierungssuche "langsam" ist. Der Registrierungszugriff ist ziemlich optimiert (und muss schneller sein als der HTTP-Kontext selbst). Überwachen Sie einfach irgendwann den Registrierungszugriff, um zu sehen, wie viele Vorgänge / Sekunde pro Sekunde ausgeführt werden sollen.
user2864740

38

Nur um Shimmy ‚s Antwort mehr klar:

var mimeType = MimeMapping.GetMimeMapping(fileName);

System.Web.dll v4.5

// Summary:
//     Returns the MIME mapping for the specified file name.
//
// Parameters:
//   fileName:
//     The file name that is used to determine the MIME type.
public static string GetMimeMapping(string fileName);

6
var mimetype = System.Web.MimeMapping.GetMimeMapping (filenamewithext);
Jay

17

Sie finden diese Informationen in der Registrierung. Der MIME-Typ für die PDF-Datei befindet sich beispielsweise im Schlüssel HKEY_CLASSES_ROOT\.pdfim Wert "Inhaltstyp":

string mimeType = Registry.GetValue(@"HKEY_CLASSES_ROOT\.pdf", "Content Type", null) as string;

Wenn Sie unter Windows arbeiten, ja. Die Grundidee ist "Finden Sie heraus, wo diese Informationen angegeben sind" und importieren Sie diese in eine Datenstruktur.
Maxwellb

3
Das OP ist mit ASP.NET verwandt ... OK, ASP.NET kann dank Mono unter Linux ausgeführt werden, aber das ist kein sehr häufiges Szenario. Ich denke, es ist ziemlich sicher anzunehmen, dass acidzombie24 Windows verwendet ...
Thomas Levesque

3
Ich würde annehmen, dass Windows eine Selbstverständlichkeit ist, wenn es um ASP.NET geht und NICHT die Verwendung von Linux spezifiziert.
Wolf5

19
Seien Sie vorsichtig mit dieser Lösung, da das Ergebnis von der vom Client installierten Software abhängt. dh ohne Office hat .doc keinen Inhaltstyp.
Marc Climent

1
Ja, Mark hat recht. Anscheinend muss Adobe Acrobat für .PDF installiert sein, um den Mimetyp zu suchen (versucht unter Windows Server 2008 R2). Das mit der Erweiterung verknüpfte Programm scheint also diesen Mimetyp beizubehalten (nicht Windows).
Vyas Bharghava

17

Ich habe ein Programm zum Abrufen und Konvertieren der Apache-Datei mime.types in ein C # geschrieben, das Dictionary<string, string>durch die Dateierweiterung eingegeben wurde. Es ist hier .

Die eigentliche Ausgabe ist diese Datei (aber Sie können sie abrufen und erneut ausführen, falls die Apache-Datei seit meiner letzten Ausführung aktualisiert wurde).

public static Dictionary<string, string> MimeTypes = new Dictionary<string, string>
{
  { "123", "application/vnd.lotus-1-2-3" },
  { "3dml", "text/vnd.in3d.3dml" },
  { "3g2", "video/3gpp2" },
  { "3gp", "video/3gpp" },
  { "7z", "application/x-7z-compressed" },
  { "aab", "application/x-authorware-bin" },
  { "aac", "audio/x-aac" },
  { "aam", "application/x-authorware-map" },
  { "aas", "application/x-authorware-seg" },
  { "abw", "application/x-abiword" },
  ...

1
Oh, das ist hübsch! Ich könnte etwas Ähnliches umgekehrt machen; um eine Klasse mit einem Dictionary<String,String[]>von jedem MIME-Typ mit all seinen Erweiterungen zu generieren . Dies ist nützlich, um Downloads anhand des übermittelten Inhaltstyps zu überprüfen und bei Bedarf eine Standarderweiterung hinzuzufügen.
Nyerguds

@ Nyerguds Das klingt nützlich. Wenn Sie eine PR durchführen möchten, um sie zu den oben genannten hinzuzufügen, würde ich sie gerne zusammenführen. Oder du kannst natürlich dein eigenes Ding machen! Aber beide Richtungen klingen nützlich.
Cymen

1
Das Hauptproblem scheint der 'Standard'-Teil zu sein ... welche der vielen, vielen Erweiterungen für einige dieser MIME-Typen die ideale Standardeinstellung ist. Ich werde wahrscheinlich sowieso eine Liste von denen fest
codieren müssen

15

Ich mag die Arbeit von Samuel Neff, aber nicht die Idee und den Aufwand, jedes Mal ein Wörterbuch zu erstellen.

Ich habe die Dinge als Schalter umstrukturiert. Ja, Sie können nicht darüber iterieren, aber in meinem Fall verwende ich es immer nur, um schnell einen Wert nachzuschlagen. Vor allem, weil es in einem Webdienst ausgeführt wird, ist das Letzte, was ich möchte, ein Haufen Overhead, während die Anwendung ihre Strukturen vorbereitet. Der Compiler verwandelt dies in eine Hash-Suche und ist daher sehr schnell.

public static string GetMimeType(string extension)
{
  if (extension == null)
    throw new ArgumentNullException("extension");

  if (extension.StartsWith("."))
    extension = extension.Substring(1);


  switch (extension.ToLower())
{
    #region Big freaking list of mime types
    case "323": return "text/h323";
    case "3g2": return "video/3gpp2";
    case "3gp": return "video/3gpp";
    case "3gp2": return "video/3gpp2";
    case "3gpp": return "video/3gpp";
    case "7z": return "application/x-7z-compressed";
    case "aa": return "audio/audible";
    case "aac": return "audio/aac";
    case "aaf": return "application/octet-stream";
    case "aax": return "audio/vnd.audible.aax";
    case "ac3": return "audio/ac3";
    case "aca": return "application/octet-stream";
    case "accda": return "application/msaccess.addin";
    case "accdb": return "application/msaccess";
    case "accdc": return "application/msaccess.cab";
    case "accde": return "application/msaccess";
    case "accdr": return "application/msaccess.runtime";
    case "accdt": return "application/msaccess";
    case "accdw": return "application/msaccess.webapplication";
    case "accft": return "application/msaccess.ftemplate";
    case "acx": return "application/internet-property-stream";
    case "addin": return "text/xml";
    case "ade": return "application/msaccess";
    case "adobebridge": return "application/x-bridge-url";
    case "adp": return "application/msaccess";
    case "adt": return "audio/vnd.dlna.adts";
    case "adts": return "audio/aac";
    case "afm": return "application/octet-stream";
    case "ai": return "application/postscript";
    case "aif": return "audio/x-aiff";
    case "aifc": return "audio/aiff";
    case "aiff": return "audio/aiff";
    case "air": return "application/vnd.adobe.air-application-installer-package+zip";
    case "amc": return "application/x-mpeg";
    case "application": return "application/x-ms-application";
    case "art": return "image/x-jg";
    case "asa": return "application/xml";
    case "asax": return "application/xml";
    case "ascx": return "application/xml";
    case "asd": return "application/octet-stream";
    case "asf": return "video/x-ms-asf";
    case "ashx": return "application/xml";
    case "asi": return "application/octet-stream";
    case "asm": return "text/plain";
    case "asmx": return "application/xml";
    case "aspx": return "application/xml";
    case "asr": return "video/x-ms-asf";
    case "asx": return "video/x-ms-asf";
    case "atom": return "application/atom+xml";
    case "au": return "audio/basic";
    case "avi": return "video/x-msvideo";
    case "axs": return "application/olescript";
    case "bas": return "text/plain";
    case "bcpio": return "application/x-bcpio";
    case "bin": return "application/octet-stream";
    case "bmp": return "image/bmp";
    case "c": return "text/plain";
    case "cab": return "application/octet-stream";
    case "caf": return "audio/x-caf";
    case "calx": return "application/vnd.ms-office.calx";
    case "cat": return "application/vnd.ms-pki.seccat";
    case "cc": return "text/plain";
    case "cd": return "text/plain";
    case "cdda": return "audio/aiff";
    case "cdf": return "application/x-cdf";
    case "cer": return "application/x-x509-ca-cert";
    case "chm": return "application/octet-stream";
    case "class": return "application/x-java-applet";
    case "clp": return "application/x-msclip";
    case "cmx": return "image/x-cmx";
    case "cnf": return "text/plain";
    case "cod": return "image/cis-cod";
    case "config": return "application/xml";
    case "contact": return "text/x-ms-contact";
    case "coverage": return "application/xml";
    case "cpio": return "application/x-cpio";
    case "cpp": return "text/plain";
    case "crd": return "application/x-mscardfile";
    case "crl": return "application/pkix-crl";
    case "crt": return "application/x-x509-ca-cert";
    case "cs": return "text/plain";
    case "csdproj": return "text/plain";
    case "csh": return "application/x-csh";
    case "csproj": return "text/plain";
    case "css": return "text/css";
    case "csv": return "text/csv";
    case "cur": return "application/octet-stream";
    case "cxx": return "text/plain";
    case "dat": return "application/octet-stream";
    case "datasource": return "application/xml";
    case "dbproj": return "text/plain";
    case "dcr": return "application/x-director";
    case "def": return "text/plain";
    case "deploy": return "application/octet-stream";
    case "der": return "application/x-x509-ca-cert";
    case "dgml": return "application/xml";
    case "dib": return "image/bmp";
    case "dif": return "video/x-dv";
    case "dir": return "application/x-director";
    case "disco": return "text/xml";
    case "dll": return "application/x-msdownload";
    case "dll.config": return "text/xml";
    case "dlm": return "text/dlm";
    case "doc": return "application/msword";
    case "docm": return "application/vnd.ms-word.document.macroenabled.12";
    case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    case "dot": return "application/msword";
    case "dotm": return "application/vnd.ms-word.template.macroenabled.12";
    case "dotx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
    case "dsp": return "application/octet-stream";
    case "dsw": return "text/plain";
    case "dtd": return "text/xml";
    case "dtsconfig": return "text/xml";
    case "dv": return "video/x-dv";
    case "dvi": return "application/x-dvi";
    case "dwf": return "drawing/x-dwf";
    case "dwp": return "application/octet-stream";
    case "dxr": return "application/x-director";
    case "eml": return "message/rfc822";
    case "emz": return "application/octet-stream";
    case "eot": return "application/octet-stream";
    case "eps": return "application/postscript";
    case "etl": return "application/etl";
    case "etx": return "text/x-setext";
    case "evy": return "application/envoy";
    case "exe": return "application/octet-stream";
    case "exe.config": return "text/xml";
    case "fdf": return "application/vnd.fdf";
    case "fif": return "application/fractals";
    case "filters": return "application/xml";
    case "fla": return "application/octet-stream";
    case "flr": return "x-world/x-vrml";
    case "flv": return "video/x-flv";
    case "fsscript": return "application/fsharp-script";
    case "fsx": return "application/fsharp-script";
    case "generictest": return "application/xml";
    case "gif": return "image/gif";
    case "group": return "text/x-ms-group";
    case "gsm": return "audio/x-gsm";
    case "gtar": return "application/x-gtar";
    case "gz": return "application/x-gzip";
    case "h": return "text/plain";
    case "hdf": return "application/x-hdf";
    case "hdml": return "text/x-hdml";
    case "hhc": return "application/x-oleobject";
    case "hhk": return "application/octet-stream";
    case "hhp": return "application/octet-stream";
    case "hlp": return "application/winhlp";
    case "hpp": return "text/plain";
    case "hqx": return "application/mac-binhex40";
    case "hta": return "application/hta";
    case "htc": return "text/x-component";
    case "htm": return "text/html";
    case "html": return "text/html";
    case "htt": return "text/webviewhtml";
    case "hxa": return "application/xml";
    case "hxc": return "application/xml";
    case "hxd": return "application/octet-stream";
    case "hxe": return "application/xml";
    case "hxf": return "application/xml";
    case "hxh": return "application/octet-stream";
    case "hxi": return "application/octet-stream";
    case "hxk": return "application/xml";
    case "hxq": return "application/octet-stream";
    case "hxr": return "application/octet-stream";
    case "hxs": return "application/octet-stream";
    case "hxt": return "text/html";
    case "hxv": return "application/xml";
    case "hxw": return "application/octet-stream";
    case "hxx": return "text/plain";
    case "i": return "text/plain";
    case "ico": return "image/x-icon";
    case "ics": return "application/octet-stream";
    case "idl": return "text/plain";
    case "ief": return "image/ief";
    case "iii": return "application/x-iphone";
    case "inc": return "text/plain";
    case "inf": return "application/octet-stream";
    case "inl": return "text/plain";
    case "ins": return "application/x-internet-signup";
    case "ipa": return "application/x-itunes-ipa";
    case "ipg": return "application/x-itunes-ipg";
    case "ipproj": return "text/plain";
    case "ipsw": return "application/x-itunes-ipsw";
    case "iqy": return "text/x-ms-iqy";
    case "isp": return "application/x-internet-signup";
    case "ite": return "application/x-itunes-ite";
    case "itlp": return "application/x-itunes-itlp";
    case "itms": return "application/x-itunes-itms";
    case "itpc": return "application/x-itunes-itpc";
    case "ivf": return "video/x-ivf";
    case "jar": return "application/java-archive";
    case "java": return "application/octet-stream";
    case "jck": return "application/liquidmotion";
    case "jcz": return "application/liquidmotion";
    case "jfif": return "image/pjpeg";
    case "jnlp": return "application/x-java-jnlp-file";
    case "jpb": return "application/octet-stream";
    case "jpe": return "image/jpeg";
    case "jpeg": return "image/jpeg";
    case "jpg": return "image/jpeg";
    case "js": return "application/x-javascript";
    case "jsx": return "text/jscript";
    case "jsxbin": return "text/plain";
    case "latex": return "application/x-latex";
    case "library-ms": return "application/windows-library+xml";
    case "lit": return "application/x-ms-reader";
    case "loadtest": return "application/xml";
    case "lpk": return "application/octet-stream";
    case "lsf": return "video/x-la-asf";
    case "lst": return "text/plain";
    case "lsx": return "video/x-la-asf";
    case "lzh": return "application/octet-stream";
    case "m13": return "application/x-msmediaview";
    case "m14": return "application/x-msmediaview";
    case "m1v": return "video/mpeg";
    case "m2t": return "video/vnd.dlna.mpeg-tts";
    case "m2ts": return "video/vnd.dlna.mpeg-tts";
    case "m2v": return "video/mpeg";
    case "m3u": return "audio/x-mpegurl";
    case "m3u8": return "audio/x-mpegurl";
    case "m4a": return "audio/m4a";
    case "m4b": return "audio/m4b";
    case "m4p": return "audio/m4p";
    case "m4r": return "audio/x-m4r";
    case "m4v": return "video/x-m4v";
    case "mac": return "image/x-macpaint";
    case "mak": return "text/plain";
    case "man": return "application/x-troff-man";
    case "manifest": return "application/x-ms-manifest";
    case "map": return "text/plain";
    case "master": return "application/xml";
    case "mda": return "application/msaccess";
    case "mdb": return "application/x-msaccess";
    case "mde": return "application/msaccess";
    case "mdp": return "application/octet-stream";
    case "me": return "application/x-troff-me";
    case "mfp": return "application/x-shockwave-flash";
    case "mht": return "message/rfc822";
    case "mhtml": return "message/rfc822";
    case "mid": return "audio/mid";
    case "midi": return "audio/mid";
    case "mix": return "application/octet-stream";
    case "mk": return "text/plain";
    case "mmf": return "application/x-smaf";
    case "mno": return "text/xml";
    case "mny": return "application/x-msmoney";
    case "mod": return "video/mpeg";
    case "mov": return "video/quicktime";
    case "movie": return "video/x-sgi-movie";
    case "mp2": return "video/mpeg";
    case "mp2v": return "video/mpeg";
    case "mp3": return "audio/mpeg";
    case "mp4": return "video/mp4";
    case "mp4v": return "video/mp4";
    case "mpa": return "video/mpeg";
    case "mpe": return "video/mpeg";
    case "mpeg": return "video/mpeg";
    case "mpf": return "application/vnd.ms-mediapackage";
    case "mpg": return "video/mpeg";
    case "mpp": return "application/vnd.ms-project";
    case "mpv2": return "video/mpeg";
    case "mqv": return "video/quicktime";
    case "ms": return "application/x-troff-ms";
    case "msi": return "application/octet-stream";
    case "mso": return "application/octet-stream";
    case "mts": return "video/vnd.dlna.mpeg-tts";
    case "mtx": return "application/xml";
    case "mvb": return "application/x-msmediaview";
    case "mvc": return "application/x-miva-compiled";
    case "mxp": return "application/x-mmxp";
    case "nc": return "application/x-netcdf";
    case "nsc": return "video/x-ms-asf";
    case "nws": return "message/rfc822";
    case "ocx": return "application/octet-stream";
    case "oda": return "application/oda";
    case "odc": return "text/x-ms-odc";
    case "odh": return "text/plain";
    case "odl": return "text/plain";
    case "odp": return "application/vnd.oasis.opendocument.presentation";
    case "ods": return "application/oleobject";
    case "odt": return "application/vnd.oasis.opendocument.text";
    case "one": return "application/onenote";
    case "onea": return "application/onenote";
    case "onepkg": return "application/onenote";
    case "onetmp": return "application/onenote";
    case "onetoc": return "application/onenote";
    case "onetoc2": return "application/onenote";
    case "orderedtest": return "application/xml";
    case "osdx": return "application/opensearchdescription+xml";
    case "p10": return "application/pkcs10";
    case "p12": return "application/x-pkcs12";
    case "p7b": return "application/x-pkcs7-certificates";
    case "p7c": return "application/pkcs7-mime";
    case "p7m": return "application/pkcs7-mime";
    case "p7r": return "application/x-pkcs7-certreqresp";
    case "p7s": return "application/pkcs7-signature";
    case "pbm": return "image/x-portable-bitmap";
    case "pcast": return "application/x-podcast";
    case "pct": return "image/pict";
    case "pcx": return "application/octet-stream";
    case "pcz": return "application/octet-stream";
    case "pdf": return "application/pdf";
    case "pfb": return "application/octet-stream";
    case "pfm": return "application/octet-stream";
    case "pfx": return "application/x-pkcs12";
    case "pgm": return "image/x-portable-graymap";
    case "pic": return "image/pict";
    case "pict": return "image/pict";
    case "pkgdef": return "text/plain";
    case "pkgundef": return "text/plain";
    case "pko": return "application/vnd.ms-pki.pko";
    case "pls": return "audio/scpls";
    case "pma": return "application/x-perfmon";
    case "pmc": return "application/x-perfmon";
    case "pml": return "application/x-perfmon";
    case "pmr": return "application/x-perfmon";
    case "pmw": return "application/x-perfmon";
    case "png": return "image/png";
    case "pnm": return "image/x-portable-anymap";
    case "pnt": return "image/x-macpaint";
    case "pntg": return "image/x-macpaint";
    case "pnz": return "image/png";
    case "pot": return "application/vnd.ms-powerpoint";
    case "potm": return "application/vnd.ms-powerpoint.template.macroenabled.12";
    case "potx": return "application/vnd.openxmlformats-officedocument.presentationml.template";
    case "ppa": return "application/vnd.ms-powerpoint";
    case "ppam": return "application/vnd.ms-powerpoint.addin.macroenabled.12";
    case "ppm": return "image/x-portable-pixmap";
    case "pps": return "application/vnd.ms-powerpoint";
    case "ppsm": return "application/vnd.ms-powerpoint.slideshow.macroenabled.12";
    case "ppsx": return "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
    case "ppt": return "application/vnd.ms-powerpoint";
    case "pptm": return "application/vnd.ms-powerpoint.presentation.macroenabled.12";
    case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
    case "prf": return "application/pics-rules";
    case "prm": return "application/octet-stream";
    case "prx": return "application/octet-stream";
    case "ps": return "application/postscript";
    case "psc1": return "application/powershell";
    case "psd": return "application/octet-stream";
    case "psess": return "application/xml";
    case "psm": return "application/octet-stream";
    case "psp": return "application/octet-stream";
    case "pub": return "application/x-mspublisher";
    case "pwz": return "application/vnd.ms-powerpoint";
    case "qht": return "text/x-html-insertion";
    case "qhtm": return "text/x-html-insertion";
    case "qt": return "video/quicktime";
    case "qti": return "image/x-quicktime";
    case "qtif": return "image/x-quicktime";
    case "qtl": return "application/x-quicktimeplayer";
    case "qxd": return "application/octet-stream";
    case "ra": return "audio/x-pn-realaudio";
    case "ram": return "audio/x-pn-realaudio";
    case "rar": return "application/octet-stream";
    case "ras": return "image/x-cmu-raster";
    case "rat": return "application/rat-file";
    case "rc": return "text/plain";
    case "rc2": return "text/plain";
    case "rct": return "text/plain";
    case "rdlc": return "application/xml";
    case "resx": return "application/xml";
    case "rf": return "image/vnd.rn-realflash";
    case "rgb": return "image/x-rgb";
    case "rgs": return "text/plain";
    case "rm": return "application/vnd.rn-realmedia";
    case "rmi": return "audio/mid";
    case "rmp": return "application/vnd.rn-rn_music_package";
    case "roff": return "application/x-troff";
    case "rpm": return "audio/x-pn-realaudio-plugin";
    case "rqy": return "text/x-ms-rqy";
    case "rtf": return "application/rtf";
    case "rtx": return "text/richtext";
    case "ruleset": return "application/xml";
    case "s": return "text/plain";
    case "safariextz": return "application/x-safari-safariextz";
    case "scd": return "application/x-msschedule";
    case "sct": return "text/scriptlet";
    case "sd2": return "audio/x-sd2";
    case "sdp": return "application/sdp";
    case "sea": return "application/octet-stream";
    case "searchconnector-ms": return "application/windows-search-connector+xml";
    case "setpay": return "application/set-payment-initiation";
    case "setreg": return "application/set-registration-initiation";
    case "settings": return "application/xml";
    case "sgimb": return "application/x-sgimb";
    case "sgml": return "text/sgml";
    case "sh": return "application/x-sh";
    case "shar": return "application/x-shar";
    case "shtml": return "text/html";
    case "sit": return "application/x-stuffit";
    case "sitemap": return "application/xml";
    case "skin": return "application/xml";
    case "sldm": return "application/vnd.ms-powerpoint.slide.macroenabled.12";
    case "sldx": return "application/vnd.openxmlformats-officedocument.presentationml.slide";
    case "slk": return "application/vnd.ms-excel";
    case "sln": return "text/plain";
    case "slupkg-ms": return "application/x-ms-license";
    case "smd": return "audio/x-smd";
    case "smi": return "application/octet-stream";
    case "smx": return "audio/x-smd";
    case "smz": return "audio/x-smd";
    case "snd": return "audio/basic";
    case "snippet": return "application/xml";
    case "snp": return "application/octet-stream";
    case "sol": return "text/plain";
    case "sor": return "text/plain";
    case "spc": return "application/x-pkcs7-certificates";
    case "spl": return "application/futuresplash";
    case "src": return "application/x-wais-source";
    case "srf": return "text/plain";
    case "ssisdeploymentmanifest": return "text/xml";
    case "ssm": return "application/streamingmedia";
    case "sst": return "application/vnd.ms-pki.certstore";
    case "stl": return "application/vnd.ms-pki.stl";
    case "sv4cpio": return "application/x-sv4cpio";
    case "sv4crc": return "application/x-sv4crc";
    case "svc": return "application/xml";
    case "swf": return "application/x-shockwave-flash";
    case "t": return "application/x-troff";
    case "tar": return "application/x-tar";
    case "tcl": return "application/x-tcl";
    case "testrunconfig": return "application/xml";
    case "testsettings": return "application/xml";
    case "tex": return "application/x-tex";
    case "texi": return "application/x-texinfo";
    case "texinfo": return "application/x-texinfo";
    case "tgz": return "application/x-compressed";
    case "thmx": return "application/vnd.ms-officetheme";
    case "thn": return "application/octet-stream";
    case "tif": return "image/tiff";
    case "tiff": return "image/tiff";
    case "tlh": return "text/plain";
    case "tli": return "text/plain";
    case "toc": return "application/octet-stream";
    case "tr": return "application/x-troff";
    case "trm": return "application/x-msterminal";
    case "trx": return "application/xml";
    case "ts": return "video/vnd.dlna.mpeg-tts";
    case "tsv": return "text/tab-separated-values";
    case "ttf": return "application/octet-stream";
    case "tts": return "video/vnd.dlna.mpeg-tts";
    case "txt": return "text/plain";
    case "u32": return "application/octet-stream";
    case "uls": return "text/iuls";
    case "user": return "text/plain";
    case "ustar": return "application/x-ustar";
    case "vb": return "text/plain";
    case "vbdproj": return "text/plain";
    case "vbk": return "video/mpeg";
    case "vbproj": return "text/plain";
    case "vbs": return "text/vbscript";
    case "vcf": return "text/x-vcard";
    case "vcproj": return "application/xml";
    case "vcs": return "text/plain";
    case "vcxproj": return "application/xml";
    case "vddproj": return "text/plain";
    case "vdp": return "text/plain";
    case "vdproj": return "text/plain";
    case "vdx": return "application/vnd.ms-visio.viewer";
    case "vml": return "text/xml";
    case "vscontent": return "application/xml";
    case "vsct": return "text/xml";
    case "vsd": return "application/vnd.visio";
    case "vsi": return "application/ms-vsi";
    case "vsix": return "application/vsix";
    case "vsixlangpack": return "text/xml";
    case "vsixmanifest": return "text/xml";
    case "vsmdi": return "application/xml";
    case "vspscc": return "text/plain";
    case "vss": return "application/vnd.visio";
    case "vsscc": return "text/plain";
    case "vssettings": return "text/xml";
    case "vssscc": return "text/plain";
    case "vst": return "application/vnd.visio";
    case "vstemplate": return "text/xml";
    case "vsto": return "application/x-ms-vsto";
    case "vsw": return "application/vnd.visio";
    case "vsx": return "application/vnd.visio";
    case "vtx": return "application/vnd.visio";
    case "wav": return "audio/wav";
    case "wave": return "audio/wav";
    case "wax": return "audio/x-ms-wax";
    case "wbk": return "application/msword";
    case "wbmp": return "image/vnd.wap.wbmp";
    case "wcm": return "application/vnd.ms-works";
    case "wdb": return "application/vnd.ms-works";
    case "wdp": return "image/vnd.ms-photo";
    case "webarchive": return "application/x-safari-webarchive";
    case "webtest": return "application/xml";
    case "wiq": return "application/xml";
    case "wiz": return "application/msword";
    case "wks": return "application/vnd.ms-works";
    case "wlmp": return "application/wlmoviemaker";
    case "wlpginstall": return "application/x-wlpg-detect";
    case "wlpginstall3": return "application/x-wlpg3-detect";
    case "wm": return "video/x-ms-wm";
    case "wma": return "audio/x-ms-wma";
    case "wmd": return "application/x-ms-wmd";
    case "wmf": return "application/x-msmetafile";
    case "wml": return "text/vnd.wap.wml";
    case "wmlc": return "application/vnd.wap.wmlc";
    case "wmls": return "text/vnd.wap.wmlscript";
    case "wmlsc": return "application/vnd.wap.wmlscriptc";
    case "wmp": return "video/x-ms-wmp";
    case "wmv": return "video/x-ms-wmv";
    case "wmx": return "video/x-ms-wmx";
    case "wmz": return "application/x-ms-wmz";
    case "wpl": return "application/vnd.ms-wpl";
    case "wps": return "application/vnd.ms-works";
    case "wri": return "application/x-mswrite";
    case "wrl": return "x-world/x-vrml";
    case "wrz": return "x-world/x-vrml";
    case "wsc": return "text/scriptlet";
    case "wsdl": return "text/xml";
    case "wvx": return "video/x-ms-wvx";
    case "x": return "application/directx";
    case "xaf": return "x-world/x-vrml";
    case "xaml": return "application/xaml+xml";
    case "xap": return "application/x-silverlight-app";
    case "xbap": return "application/x-ms-xbap";
    case "xbm": return "image/x-xbitmap";
    case "xdr": return "text/plain";
    case "xht": return "application/xhtml+xml";
    case "xhtml": return "application/xhtml+xml";
    case "xla": return "application/vnd.ms-excel";
    case "xlam": return "application/vnd.ms-excel.addin.macroenabled.12";
    case "xlc": return "application/vnd.ms-excel";
    case "xld": return "application/vnd.ms-excel";
    case "xlk": return "application/vnd.ms-excel";
    case "xll": return "application/vnd.ms-excel";
    case "xlm": return "application/vnd.ms-excel";
    case "xls": return "application/vnd.ms-excel";
    case "xlsb": return "application/vnd.ms-excel.sheet.binary.macroenabled.12";
    case "xlsm": return "application/vnd.ms-excel.sheet.macroenabled.12";
    case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    case "xlt": return "application/vnd.ms-excel";
    case "xltm": return "application/vnd.ms-excel.template.macroenabled.12";
    case "xltx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
    case "xlw": return "application/vnd.ms-excel";
    case "xml": return "text/xml";
    case "xmta": return "application/xml";
    case "xof": return "x-world/x-vrml";
    case "xoml": return "text/plain";
    case "xpm": return "image/x-xpixmap";
    case "xps": return "application/vnd.ms-xpsdocument";
    case "xrm-ms": return "text/xml";
    case "xsc": return "application/xml";
    case "xsd": return "text/xml";
    case "xsf": return "text/xml";
    case "xsl": return "text/xml";
    case "xslt": return "text/xml";
    case "xsn": return "application/octet-stream";
    case "xss": return "application/xml";
    case "xtp": return "application/octet-stream";
    case "xwd": return "image/x-xwindowdump";
    case "z": return "application/x-compress";
    case "zip": return "application/x-zip-compressed";
  #endregion
    default: return "application/octet-stream";
  }
}

1
Hat jemand die Umkehrung dieser Funktion? Erweiterung nach MIME-Typ einstellen? nur faul sein: P
FabioG

5
@FabioG Ich bin mir nicht sicher, ob das für dich so nützlich sein wird. Beispielsweise hätte der MIME-Typ "application / xml" 43 übereinstimmende Erweiterungen aus dieser Liste.
Barrie

@Barrie Könnten Sie so etwas tun: Verwenden Sie einfach die erste in der Liste, um eine Standarderweiterung (einen Stich auf den kleinsten gemeinsamen Nenner) zu erhalten, z. B. "application / xml" => .xml und "image / jpeg" =>. Jpg welche würde auf den meisten Betriebssystemen nicht funktionieren? Was vermisse ich? Vermutlich wäre dies für einige Standardtypen gut, aber in dieser langen Liste scheitern sie an vielen. Gedanken?
MemeDeveloper

5
Overhead kann einfach dadurch vermieden werden, dass es statisch ist. Ein Switch-Case mit Strings ist jedoch eine schreckliche, schreckliche Sache, wenn es um "Overhead" geht. Einfach gesagt ... auf Prozessorebene ist alles nur Prüfen und Springen; if/ else, while, for... nichts davon tatsächlich existiert. switch/ case, Angewandt auf kleine ganzzahlige Werte jedoch typischerweise in enums gefunden, tut exist. Es ist eine herrlich elegante kleine Operation. Es funktioniert auch überhaupt nicht mit Strings, was bedeutet, dass das, was Sie geschrieben haben, wirklich nur eine Reihe von String-Vergleichen ist. Ein Dictionary-Objekt schlägt das jeden Tag.
Nyerguds

9

eine Kombination beider hier vorgestellten Lösungen:

using System;
using System.Collections.Generic;

namespace Mime
{
    class Mime
    {

        public static string GetMimeType(string fileName)
        {
            if (string.IsNullOrEmpty(fileName) || string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("filename must contain a filename");
            }
            string extension = System.IO.Path.GetExtension(fileName).ToLower();

            if (!extension.StartsWith("."))
            {
                extension = "." + extension;
            }


            string mime;

            if (_mappings.TryGetValue(extension, out mime))
                return mime;
            if (GetWindowsMimeType(extension, out mime))
            {
                _mappings.Add(extension, mime);
                return mime;
            }
            return "application/octet-stream";
        }

        public static bool GetWindowsMimeType(string ext, out string mime)
        {
            mime="application/octet-stream";
            Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);

            if (regKey != null)
            { 
             object val=regKey.GetValue("Content Type") ;
             if (val != null)
             {
                 string strval = val.ToString();
                 if(!(string.IsNullOrEmpty(strval)||string.IsNullOrWhiteSpace(strval)))
                 {
                     mime=strval;
                     return true;
                 }
             }
            }
            return false;
        }

        static IDictionary<string, string> _mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {

        #region Big freaking list of mime types
        // combination of values from Windows 7 Registry and 
        // from C:\Windows\System32\inetsrv\config\applicationHost.config
        // some added, including .7z and .dat
        {".323", "text/h323"},
        {".3g2", "video/3gpp2"},
        {".3gp", "video/3gpp"},
        {".3gp2", "video/3gpp2"},
        {".3gpp", "video/3gpp"},
        {".7z", "application/x-7z-compressed"},
        {".aa", "audio/audible"},
        {".AAC", "audio/aac"},
        {".aaf", "application/octet-stream"},
        {".aax", "audio/vnd.audible.aax"},
        {".ac3", "audio/ac3"},
        {".aca", "application/octet-stream"},
        {".accda", "application/msaccess.addin"},
        {".accdb", "application/msaccess"},
        {".accdc", "application/msaccess.cab"},
        {".accde", "application/msaccess"},
        {".accdr", "application/msaccess.runtime"},
        {".accdt", "application/msaccess"},
        {".accdw", "application/msaccess.webapplication"},
        {".accft", "application/msaccess.ftemplate"},
        {".acx", "application/internet-property-stream"},
        {".AddIn", "text/xml"},
        {".ade", "application/msaccess"},
        {".adobebridge", "application/x-bridge-url"},
        {".adp", "application/msaccess"},
        {".ADT", "audio/vnd.dlna.adts"},
        {".ADTS", "audio/aac"},
        {".afm", "application/octet-stream"},
        {".ai", "application/postscript"},
        {".aif", "audio/x-aiff"},
        {".aifc", "audio/aiff"},
        {".aiff", "audio/aiff"},
        {".air", "application/vnd.adobe.air-application-installer-package+zip"},
        {".amc", "application/x-mpeg"},
        {".application", "application/x-ms-application"},
        {".art", "image/x-jg"},
        {".asa", "application/xml"},
        {".asax", "application/xml"},
        {".ascx", "application/xml"},
        {".asd", "application/octet-stream"},
        {".asf", "video/x-ms-asf"},
        {".ashx", "application/xml"},
        {".asi", "application/octet-stream"},
        {".asm", "text/plain"},
        {".asmx", "application/xml"},
        {".aspx", "application/xml"},
        {".asr", "video/x-ms-asf"},
        {".asx", "video/x-ms-asf"},
        {".atom", "application/atom+xml"},
        {".au", "audio/basic"},
        {".avi", "video/x-msvideo"},
        {".axs", "application/olescript"},
        {".bas", "text/plain"},
        {".bcpio", "application/x-bcpio"},
        {".bin", "application/octet-stream"},
        {".bmp", "image/bmp"},
        {".c", "text/plain"},
        {".cab", "application/octet-stream"},
        {".caf", "audio/x-caf"},
        {".calx", "application/vnd.ms-office.calx"},
        {".cat", "application/vnd.ms-pki.seccat"},
        {".cc", "text/plain"},
        {".cd", "text/plain"},
        {".cdda", "audio/aiff"},
        {".cdf", "application/x-cdf"},
        {".cer", "application/x-x509-ca-cert"},
        {".chm", "application/octet-stream"},
        {".class", "application/x-java-applet"},
        {".clp", "application/x-msclip"},
        {".cmx", "image/x-cmx"},
        {".cnf", "text/plain"},
        {".cod", "image/cis-cod"},
        {".config", "application/xml"},
        {".contact", "text/x-ms-contact"},
        {".coverage", "application/xml"},
        {".cpio", "application/x-cpio"},
        {".cpp", "text/plain"},
        {".crd", "application/x-mscardfile"},
        {".crl", "application/pkix-crl"},
        {".crt", "application/x-x509-ca-cert"},
        {".cs", "text/plain"},
        {".csdproj", "text/plain"},
        {".csh", "application/x-csh"},
        {".csproj", "text/plain"},
        {".css", "text/css"},
        {".csv", "text/csv"},
        {".cur", "application/octet-stream"},
        {".cxx", "text/plain"},
        {".dat", "application/octet-stream"},
        {".datasource", "application/xml"},
        {".dbproj", "text/plain"},
        {".dcr", "application/x-director"},
        {".def", "text/plain"},
        {".deploy", "application/octet-stream"},
        {".der", "application/x-x509-ca-cert"},
        {".dgml", "application/xml"},
        {".dib", "image/bmp"},
        {".dif", "video/x-dv"},
        {".dir", "application/x-director"},
        {".disco", "text/xml"},
        {".dll", "application/x-msdownload"},
        {".dll.config", "text/xml"},
        {".dlm", "text/dlm"},
        {".doc", "application/msword"},
        {".docm", "application/vnd.ms-word.document.macroEnabled.12"},
        {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
        {".dot", "application/msword"},
        {".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
        {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
        {".dsp", "application/octet-stream"},
        {".dsw", "text/plain"},
        {".dtd", "text/xml"},
        {".dtsConfig", "text/xml"},
        {".dv", "video/x-dv"},
        {".dvi", "application/x-dvi"},
        {".dwf", "drawing/x-dwf"},
        {".dwp", "application/octet-stream"},
        {".dxr", "application/x-director"},
        {".eml", "message/rfc822"},
        {".emz", "application/octet-stream"},
        {".eot", "application/octet-stream"},
        {".eps", "application/postscript"},
        {".etl", "application/etl"},
        {".etx", "text/x-setext"},
        {".evy", "application/envoy"},
        {".exe", "application/octet-stream"},
        {".exe.config", "text/xml"},
        {".fdf", "application/vnd.fdf"},
        {".fif", "application/fractals"},
        {".filters", "Application/xml"},
        {".fla", "application/octet-stream"},
        {".flr", "x-world/x-vrml"},
        {".flv", "video/x-flv"},
        {".fsscript", "application/fsharp-script"},
        {".fsx", "application/fsharp-script"},
        {".generictest", "application/xml"},
        {".gif", "image/gif"},
        {".group", "text/x-ms-group"},
        {".gsm", "audio/x-gsm"},
        {".gtar", "application/x-gtar"},
        {".gz", "application/x-gzip"},
        {".h", "text/plain"},
        {".hdf", "application/x-hdf"},
        {".hdml", "text/x-hdml"},
        {".hhc", "application/x-oleobject"},
        {".hhk", "application/octet-stream"},
        {".hhp", "application/octet-stream"},
        {".hlp", "application/winhlp"},
        {".hpp", "text/plain"},
        {".hqx", "application/mac-binhex40"},
        {".hta", "application/hta"},
        {".htc", "text/x-component"},
        {".htm", "text/html"},
        {".html", "text/html"},
        {".htt", "text/webviewhtml"},
        {".hxa", "application/xml"},
        {".hxc", "application/xml"},
        {".hxd", "application/octet-stream"},
        {".hxe", "application/xml"},
        {".hxf", "application/xml"},
        {".hxh", "application/octet-stream"},
        {".hxi", "application/octet-stream"},
        {".hxk", "application/xml"},
        {".hxq", "application/octet-stream"},
        {".hxr", "application/octet-stream"},
        {".hxs", "application/octet-stream"},
        {".hxt", "text/html"},
        {".hxv", "application/xml"},
        {".hxw", "application/octet-stream"},
        {".hxx", "text/plain"},
        {".i", "text/plain"},
        {".ico", "image/x-icon"},
        {".ics", "application/octet-stream"},
        {".idl", "text/plain"},
        {".ief", "image/ief"},
        {".iii", "application/x-iphone"},
        {".inc", "text/plain"},
        {".inf", "application/octet-stream"},
        {".inl", "text/plain"},
        {".ins", "application/x-internet-signup"},
        {".ipa", "application/x-itunes-ipa"},
        {".ipg", "application/x-itunes-ipg"},
        {".ipproj", "text/plain"},
        {".ipsw", "application/x-itunes-ipsw"},
        {".iqy", "text/x-ms-iqy"},
        {".isp", "application/x-internet-signup"},
        {".ite", "application/x-itunes-ite"},
        {".itlp", "application/x-itunes-itlp"},
        {".itms", "application/x-itunes-itms"},
        {".itpc", "application/x-itunes-itpc"},
        {".IVF", "video/x-ivf"},
        {".jar", "application/java-archive"},
        {".java", "application/octet-stream"},
        {".jck", "application/liquidmotion"},
        {".jcz", "application/liquidmotion"},
        {".jfif", "image/pjpeg"},
        {".jnlp", "application/x-java-jnlp-file"},
        {".jpb", "application/octet-stream"},
        {".jpe", "image/jpeg"},
        {".jpeg", "image/jpeg"},
        {".jpg", "image/jpeg"},
        {".js", "application/x-javascript"},
        {".jsx", "text/jscript"},
        {".jsxbin", "text/plain"},
        {".latex", "application/x-latex"},
        {".library-ms", "application/windows-library+xml"},
        {".lit", "application/x-ms-reader"},
        {".loadtest", "application/xml"},
        {".lpk", "application/octet-stream"},
        {".lsf", "video/x-la-asf"},
        {".lst", "text/plain"},
        {".lsx", "video/x-la-asf"},
        {".lzh", "application/octet-stream"},
        {".m13", "application/x-msmediaview"},
        {".m14", "application/x-msmediaview"},
        {".m1v", "video/mpeg"},
        {".m2t", "video/vnd.dlna.mpeg-tts"},
        {".m2ts", "video/vnd.dlna.mpeg-tts"},
        {".m2v", "video/mpeg"},
        {".m3u", "audio/x-mpegurl"},
        {".m3u8", "audio/x-mpegurl"},
        {".m4a", "audio/m4a"},
        {".m4b", "audio/m4b"},
        {".m4p", "audio/m4p"},
        {".m4r", "audio/x-m4r"},
        {".m4v", "video/x-m4v"},
        {".mac", "image/x-macpaint"},
        {".mak", "text/plain"},
        {".man", "application/x-troff-man"},
        {".manifest", "application/x-ms-manifest"},
        {".map", "text/plain"},
        {".master", "application/xml"},
        {".mda", "application/msaccess"},
        {".mdb", "application/x-msaccess"},
        {".mde", "application/msaccess"},
        {".mdp", "application/octet-stream"},
        {".me", "application/x-troff-me"},
        {".mfp", "application/x-shockwave-flash"},
        {".mht", "message/rfc822"},
        {".mhtml", "message/rfc822"},
        {".mid", "audio/mid"},
        {".midi", "audio/mid"},
        {".mix", "application/octet-stream"},
        {".mk", "text/plain"},
        {".mmf", "application/x-smaf"},
        {".mno", "text/xml"},
        {".mny", "application/x-msmoney"},
        {".mod", "video/mpeg"},
        {".mov", "video/quicktime"},
        {".movie", "video/x-sgi-movie"},
        {".mp2", "video/mpeg"},
        {".mp2v", "video/mpeg"},
        {".mp3", "audio/mpeg"},
        {".mp4", "video/mp4"},
        {".mp4v", "video/mp4"},
        {".mpa", "video/mpeg"},
        {".mpe", "video/mpeg"},
        {".mpeg", "video/mpeg"},
        {".mpf", "application/vnd.ms-mediapackage"},
        {".mpg", "video/mpeg"},
        {".mpp", "application/vnd.ms-project"},
        {".mpv2", "video/mpeg"},
        {".mqv", "video/quicktime"},
        {".ms", "application/x-troff-ms"},
        {".msi", "application/octet-stream"},
        {".mso", "application/octet-stream"},
        {".mts", "video/vnd.dlna.mpeg-tts"},
        {".mtx", "application/xml"},
        {".mvb", "application/x-msmediaview"},
        {".mvc", "application/x-miva-compiled"},
        {".mxp", "application/x-mmxp"},
        {".nc", "application/x-netcdf"},
        {".nsc", "video/x-ms-asf"},
        {".nws", "message/rfc822"},
        {".ocx", "application/octet-stream"},
        {".oda", "application/oda"},
        {".odc", "text/x-ms-odc"},
        {".odh", "text/plain"},
        {".odl", "text/plain"},
        {".odp", "application/vnd.oasis.opendocument.presentation"},
        {".ods", "application/oleobject"},
        {".odt", "application/vnd.oasis.opendocument.text"},
        {".one", "application/onenote"},
        {".onea", "application/onenote"},
        {".onepkg", "application/onenote"},
        {".onetmp", "application/onenote"},
        {".onetoc", "application/onenote"},
        {".onetoc2", "application/onenote"},
        {".orderedtest", "application/xml"},
        {".osdx", "application/opensearchdescription+xml"},
        {".p10", "application/pkcs10"},
        {".p12", "application/x-pkcs12"},
        {".p7b", "application/x-pkcs7-certificates"},
        {".p7c", "application/pkcs7-mime"},
        {".p7m", "application/pkcs7-mime"},
        {".p7r", "application/x-pkcs7-certreqresp"},
        {".p7s", "application/pkcs7-signature"},
        {".pbm", "image/x-portable-bitmap"},
        {".pcast", "application/x-podcast"},
        {".pct", "image/pict"},
        {".pcx", "application/octet-stream"},
        {".pcz", "application/octet-stream"},
        {".pdf", "application/pdf"},
        {".pfb", "application/octet-stream"},
        {".pfm", "application/octet-stream"},
        {".pfx", "application/x-pkcs12"},
        {".pgm", "image/x-portable-graymap"},
        {".pic", "image/pict"},
        {".pict", "image/pict"},
        {".pkgdef", "text/plain"},
        {".pkgundef", "text/plain"},
        {".pko", "application/vnd.ms-pki.pko"},
        {".pls", "audio/scpls"},
        {".pma", "application/x-perfmon"},
        {".pmc", "application/x-perfmon"},
        {".pml", "application/x-perfmon"},
        {".pmr", "application/x-perfmon"},
        {".pmw", "application/x-perfmon"},
        {".png", "image/png"},
        {".pnm", "image/x-portable-anymap"},
        {".pnt", "image/x-macpaint"},
        {".pntg", "image/x-macpaint"},
        {".pnz", "image/png"},
        {".pot", "application/vnd.ms-powerpoint"},
        {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
        {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
        {".ppa", "application/vnd.ms-powerpoint"},
        {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
        {".ppm", "image/x-portable-pixmap"},
        {".pps", "application/vnd.ms-powerpoint"},
        {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
        {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
        {".ppt", "application/vnd.ms-powerpoint"},
        {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
        {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
        {".prf", "application/pics-rules"},
        {".prm", "application/octet-stream"},
        {".prx", "application/octet-stream"},
        {".ps", "application/postscript"},
        {".psc1", "application/PowerShell"},
        {".psd", "application/octet-stream"},
        {".psess", "application/xml"},
        {".psm", "application/octet-stream"},
        {".psp", "application/octet-stream"},
        {".pub", "application/x-mspublisher"},
        {".pwz", "application/vnd.ms-powerpoint"},
        {".qht", "text/x-html-insertion"},
        {".qhtm", "text/x-html-insertion"},
        {".qt", "video/quicktime"},
        {".qti", "image/x-quicktime"},
        {".qtif", "image/x-quicktime"},
        {".qtl", "application/x-quicktimeplayer"},
        {".qxd", "application/octet-stream"},
        {".ra", "audio/x-pn-realaudio"},
        {".ram", "audio/x-pn-realaudio"},
        {".rar", "application/octet-stream"},
        {".ras", "image/x-cmu-raster"},
        {".rat", "application/rat-file"},
        {".rc", "text/plain"},
        {".rc2", "text/plain"},
        {".rct", "text/plain"},
        {".rdlc", "application/xml"},
        {".resx", "application/xml"},
        {".rf", "image/vnd.rn-realflash"},
        {".rgb", "image/x-rgb"},
        {".rgs", "text/plain"},
        {".rm", "application/vnd.rn-realmedia"},
        {".rmi", "audio/mid"},
        {".rmp", "application/vnd.rn-rn_music_package"},
        {".roff", "application/x-troff"},
        {".rpm", "audio/x-pn-realaudio-plugin"},
        {".rqy", "text/x-ms-rqy"},
        {".rtf", "application/rtf"},
        {".rtx", "text/richtext"},
        {".ruleset", "application/xml"},
        {".s", "text/plain"},
        {".safariextz", "application/x-safari-safariextz"},
        {".scd", "application/x-msschedule"},
        {".sct", "text/scriptlet"},
        {".sd2", "audio/x-sd2"},
        {".sdp", "application/sdp"},
        {".sea", "application/octet-stream"},
        {".searchConnector-ms", "application/windows-search-connector+xml"},
        {".setpay", "application/set-payment-initiation"},
        {".setreg", "application/set-registration-initiation"},
        {".settings", "application/xml"},
        {".sgimb", "application/x-sgimb"},
        {".sgml", "text/sgml"},
        {".sh", "application/x-sh"},
        {".shar", "application/x-shar"},
        {".shtml", "text/html"},
        {".sit", "application/x-stuffit"},
        {".sitemap", "application/xml"},
        {".skin", "application/xml"},
        {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
        {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
        {".slk", "application/vnd.ms-excel"},
        {".sln", "text/plain"},
        {".slupkg-ms", "application/x-ms-license"},
        {".smd", "audio/x-smd"},
        {".smi", "application/octet-stream"},
        {".smx", "audio/x-smd"},
        {".smz", "audio/x-smd"},
        {".snd", "audio/basic"},
        {".snippet", "application/xml"},
        {".snp", "application/octet-stream"},
        {".sol", "text/plain"},
        {".sor", "text/plain"},
        {".spc", "application/x-pkcs7-certificates"},
        {".spl", "application/futuresplash"},
        {".src", "application/x-wais-source"},
        {".srf", "text/plain"},
        {".SSISDeploymentManifest", "text/xml"},
        {".ssm", "application/streamingmedia"},
        {".sst", "application/vnd.ms-pki.certstore"},
        {".stl", "application/vnd.ms-pki.stl"},
        {".sv4cpio", "application/x-sv4cpio"},
        {".sv4crc", "application/x-sv4crc"},
        {".svc", "application/xml"},
        {".swf", "application/x-shockwave-flash"},
        {".t", "application/x-troff"},
        {".tar", "application/x-tar"},
        {".tcl", "application/x-tcl"},
        {".testrunconfig", "application/xml"},
        {".testsettings", "application/xml"},
        {".tex", "application/x-tex"},
        {".texi", "application/x-texinfo"},
        {".texinfo", "application/x-texinfo"},
        {".tgz", "application/x-compressed"},
        {".thmx", "application/vnd.ms-officetheme"},
        {".thn", "application/octet-stream"},
        {".tif", "image/tiff"},
        {".tiff", "image/tiff"},
        {".tlh", "text/plain"},
        {".tli", "text/plain"},
        {".toc", "application/octet-stream"},
        {".tr", "application/x-troff"},
        {".trm", "application/x-msterminal"},
        {".trx", "application/xml"},
        {".ts", "video/vnd.dlna.mpeg-tts"},
        {".tsv", "text/tab-separated-values"},
        {".ttf", "application/octet-stream"},
        {".tts", "video/vnd.dlna.mpeg-tts"},
        {".txt", "text/plain"},
        {".u32", "application/octet-stream"},
        {".uls", "text/iuls"},
        {".user", "text/plain"},
        {".ustar", "application/x-ustar"},
        {".vb", "text/plain"},
        {".vbdproj", "text/plain"},
        {".vbk", "video/mpeg"},
        {".vbproj", "text/plain"},
        {".vbs", "text/vbscript"},
        {".vcf", "text/x-vcard"},
        {".vcproj", "Application/xml"},
        {".vcs", "text/plain"},
        {".vcxproj", "Application/xml"},
        {".vddproj", "text/plain"},
        {".vdp", "text/plain"},
        {".vdproj", "text/plain"},
        {".vdx", "application/vnd.ms-visio.viewer"},
        {".vml", "text/xml"},
        {".vscontent", "application/xml"},
        {".vsct", "text/xml"},
        {".vsd", "application/vnd.visio"},
        {".vsi", "application/ms-vsi"},
        {".vsix", "application/vsix"},
        {".vsixlangpack", "text/xml"},
        {".vsixmanifest", "text/xml"},
        {".vsmdi", "application/xml"},
        {".vspscc", "text/plain"},
        {".vss", "application/vnd.visio"},
        {".vsscc", "text/plain"},
        {".vssettings", "text/xml"},
        {".vssscc", "text/plain"},
        {".vst", "application/vnd.visio"},
        {".vstemplate", "text/xml"},
        {".vsto", "application/x-ms-vsto"},
        {".vsw", "application/vnd.visio"},
        {".vsx", "application/vnd.visio"},
        {".vtx", "application/vnd.visio"},
        {".wav", "audio/wav"},
        {".wave", "audio/wav"},
        {".wax", "audio/x-ms-wax"},
        {".wbk", "application/msword"},
        {".wbmp", "image/vnd.wap.wbmp"},
        {".wcm", "application/vnd.ms-works"},
        {".wdb", "application/vnd.ms-works"},
        {".wdp", "image/vnd.ms-photo"},
        {".webarchive", "application/x-safari-webarchive"},
        {".webtest", "application/xml"},
        {".wiq", "application/xml"},
        {".wiz", "application/msword"},
        {".wks", "application/vnd.ms-works"},
        {".WLMP", "application/wlmoviemaker"},
        {".wlpginstall", "application/x-wlpg-detect"},
        {".wlpginstall3", "application/x-wlpg3-detect"},
        {".wm", "video/x-ms-wm"},
        {".wma", "audio/x-ms-wma"},
        {".wmd", "application/x-ms-wmd"},
        {".wmf", "application/x-msmetafile"},
        {".wml", "text/vnd.wap.wml"},
        {".wmlc", "application/vnd.wap.wmlc"},
        {".wmls", "text/vnd.wap.wmlscript"},
        {".wmlsc", "application/vnd.wap.wmlscriptc"},
        {".wmp", "video/x-ms-wmp"},
        {".wmv", "video/x-ms-wmv"},
        {".wmx", "video/x-ms-wmx"},
        {".wmz", "application/x-ms-wmz"},
        {".wpl", "application/vnd.ms-wpl"},
        {".wps", "application/vnd.ms-works"},
        {".wri", "application/x-mswrite"},
        {".wrl", "x-world/x-vrml"},
        {".wrz", "x-world/x-vrml"},
        {".wsc", "text/scriptlet"},
        {".wsdl", "text/xml"},
        {".wvx", "video/x-ms-wvx"},
        {".x", "application/directx"},
        {".xaf", "x-world/x-vrml"},
        {".xaml", "application/xaml+xml"},
        {".xap", "application/x-silverlight-app"},
        {".xbap", "application/x-ms-xbap"},
        {".xbm", "image/x-xbitmap"},
        {".xdr", "text/plain"},
        {".xht", "application/xhtml+xml"},
        {".xhtml", "application/xhtml+xml"},
        {".xla", "application/vnd.ms-excel"},
        {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
        {".xlc", "application/vnd.ms-excel"},
        {".xld", "application/vnd.ms-excel"},
        {".xlk", "application/vnd.ms-excel"},
        {".xll", "application/vnd.ms-excel"},
        {".xlm", "application/vnd.ms-excel"},
        {".xls", "application/vnd.ms-excel"},
        {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
        {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
        {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
        {".xlt", "application/vnd.ms-excel"},
        {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
        {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
        {".xlw", "application/vnd.ms-excel"},
        {".xml", "text/xml"},
        {".xmta", "application/xml"},
        {".xof", "x-world/x-vrml"},
        {".XOML", "text/plain"},
        {".xpm", "image/x-xpixmap"},
        {".xps", "application/vnd.ms-xpsdocument"},
        {".xrm-ms", "text/xml"},
        {".xsc", "application/xml"},
        {".xsd", "text/xml"},
        {".xsf", "text/xml"},
        {".xsl", "text/xml"},
        {".xslt", "text/xml"},
        {".xsn", "application/octet-stream"},
        {".xss", "application/xml"},
        {".xtp", "application/octet-stream"},
        {".xwd", "image/x-xwindowdump"},
        {".z", "application/x-compress"},
        {".zip", "application/x-zip-compressed"},
        #endregion

        };

    }
}

1
Wenn die Registrierung erfolgreich ist,
speichern Sie

8

Ich weiß, dass die Frage für C # ist. Ich möchte nur im Javascript-Format bleiben, weil ich gerade die Antwort von Samuel konvertiert habe:

export const contentTypes = {

".323": "text/h323",
".3g2": "video/3gpp2",
".3gp": "video/3gpp",
".3gp2": "video/3gpp2",
".3gpp": "video/3gpp",
".7z": "application/x-7z-compressed",
".aa": "audio/audible",
".AAC": "audio/aac",
".aaf": "application/octet-stream",
".aax": "audio/vnd.audible.aax",
".ac3": "audio/ac3",
".aca": "application/octet-stream",
".accda": "application/msaccess.addin",
".accdb": "application/msaccess",
".accdc": "application/msaccess.cab",
".accde": "application/msaccess",
".accdr": "application/msaccess.runtime",
".accdt": "application/msaccess",
".accdw": "application/msaccess.webapplication",
".accft": "application/msaccess.ftemplate",
".acx": "application/internet-property-stream",
".AddIn": "text/xml",
".ade": "application/msaccess",
".adobebridge": "application/x-bridge-url",
".adp": "application/msaccess",
".ADT": "audio/vnd.dlna.adts",
".ADTS": "audio/aac",
".afm": "application/octet-stream",
".ai": "application/postscript",
".aif": "audio/x-aiff",
".aifc": "audio/aiff",
".aiff": "audio/aiff",
".air": "application/vnd.adobe.air-application-installer-package+zip",
".amc": "application/x-mpeg",
".application": "application/x-ms-application",
".art": "image/x-jg",
".asa": "application/xml",
".asax": "application/xml",
".ascx": "application/xml",
".asd": "application/octet-stream",
".asf": "video/x-ms-asf",
".ashx": "application/xml",
".asi": "application/octet-stream",
".asm": "text/plain",
".asmx": "application/xml",
".aspx": "application/xml",
".asr": "video/x-ms-asf",
".asx": "video/x-ms-asf",
".atom": "application/atom+xml",
".au": "audio/basic",
".avi": "video/x-msvideo",
".axs": "application/olescript",
".bas": "text/plain",
".bcpio": "application/x-bcpio",
".bin": "application/octet-stream",
".bmp": "image/bmp",
".c": "text/plain",
".cab": "application/octet-stream",
".caf": "audio/x-caf",
".calx": "application/vnd.ms-office.calx",
".cat": "application/vnd.ms-pki.seccat",
".cc": "text/plain",
".cd": "text/plain",
".cdda": "audio/aiff",
".cdf": "application/x-cdf",
".cer": "application/x-x509-ca-cert",
".chm": "application/octet-stream",
".class": "application/x-java-applet",
".clp": "application/x-msclip",
".cmx": "image/x-cmx",
".cnf": "text/plain",
".cod": "image/cis-cod",
".config": "application/xml",
".contact": "text/x-ms-contact",
".coverage": "application/xml",
".cpio": "application/x-cpio",
".cpp": "text/plain",
".crd": "application/x-mscardfile",
".crl": "application/pkix-crl",
".crt": "application/x-x509-ca-cert",
".cs": "text/plain",
".csdproj": "text/plain",
".csh": "application/x-csh",
".csproj": "text/plain",
".css": "text/css",
".csv": "text/csv",
".cur": "application/octet-stream",
".cxx": "text/plain",
".dat": "application/octet-stream",
".datasource": "application/xml",
".dbproj": "text/plain",
".dcr": "application/x-director",
".def": "text/plain",
".deploy": "application/octet-stream",
".der": "application/x-x509-ca-cert",
".dgml": "application/xml",
".dib": "image/bmp",
".dif": "video/x-dv",
".dir": "application/x-director",
".disco": "text/xml",
".dll": "application/x-msdownload",
".dll.config": "text/xml",
".dlm": "text/dlm",
".doc": "application/msword",
".docm": "application/vnd.ms-word.document.macroEnabled.12",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".dot": "application/msword",
".dotm": "application/vnd.ms-word.template.macroEnabled.12",
".dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
".dsp": "application/octet-stream",
".dsw": "text/plain",
".dtd": "text/xml",
".dtsConfig": "text/xml",
".dv": "video/x-dv",
".dvi": "application/x-dvi",
".dwf": "drawing/x-dwf",
".dwp": "application/octet-stream",
".dxr": "application/x-director",
".eml": "message/rfc822",
".emz": "application/octet-stream",
".eot": "application/octet-stream",
".eps": "application/postscript",
".etl": "application/etl",
".etx": "text/x-setext",
".evy": "application/envoy",
".exe": "application/octet-stream",
".exe.config": "text/xml",
".fdf": "application/vnd.fdf",
".fif": "application/fractals",
".filters": "Application/xml",
".fla": "application/octet-stream",
".flr": "x-world/x-vrml",
".flv": "video/x-flv",
".fsscript": "application/fsharp-script",
".fsx": "application/fsharp-script",
".generictest": "application/xml",
".gif": "image/gif",
".group": "text/x-ms-group",
".gsm": "audio/x-gsm",
".gtar": "application/x-gtar",
".gz": "application/x-gzip",
".h": "text/plain",
".hdf": "application/x-hdf",
".hdml": "text/x-hdml",
".hhc": "application/x-oleobject",
".hhk": "application/octet-stream",
".hhp": "application/octet-stream",
".hlp": "application/winhlp",
".hpp": "text/plain",
".hqx": "application/mac-binhex40",
".hta": "application/hta",
".htc": "text/x-component",
".htm": "text/html",
".html": "text/html",
".htt": "text/webviewhtml",
".hxa": "application/xml",
".hxc": "application/xml",
".hxd": "application/octet-stream",
".hxe": "application/xml",
".hxf": "application/xml",
".hxh": "application/octet-stream",
".hxi": "application/octet-stream",
".hxk": "application/xml",
".hxq": "application/octet-stream",
".hxr": "application/octet-stream",
".hxs": "application/octet-stream",
".hxt": "text/html",
".hxv": "application/xml",
".hxw": "application/octet-stream",
".hxx": "text/plain",
".i": "text/plain",
".ico": "image/x-icon",
".ics": "application/octet-stream",
".idl": "text/plain",
".ief": "image/ief",
".iii": "application/x-iphone",
".inc": "text/plain",
".inf": "application/octet-stream",
".inl": "text/plain",
".ins": "application/x-internet-signup",
".ipa": "application/x-itunes-ipa",
".ipg": "application/x-itunes-ipg",
".ipproj": "text/plain",
".ipsw": "application/x-itunes-ipsw",
".iqy": "text/x-ms-iqy",
".isp": "application/x-internet-signup",
".ite": "application/x-itunes-ite",
".itlp": "application/x-itunes-itlp",
".itms": "application/x-itunes-itms",
".itpc": "application/x-itunes-itpc",
".IVF": "video/x-ivf",
".jar": "application/java-archive",
".java": "application/octet-stream",
".jck": "application/liquidmotion",
".jcz": "application/liquidmotion",
".jfif": "image/pjpeg",
".jnlp": "application/x-java-jnlp-file",
".jpb": "application/octet-stream",
".jpe": "image/jpeg",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".js": "application/x-javascript",
".json": "application/json",
".jsx": "text/jscript",
".jsxbin": "text/plain",
".latex": "application/x-latex",
".library-ms": "application/windows-library+xml",
".lit": "application/x-ms-reader",
".loadtest": "application/xml",
".lpk": "application/octet-stream",
".lsf": "video/x-la-asf",
".lst": "text/plain",
".lsx": "video/x-la-asf",
".lzh": "application/octet-stream",
".m13": "application/x-msmediaview",
".m14": "application/x-msmediaview",
".m1v": "video/mpeg",
".m2t": "video/vnd.dlna.mpeg-tts",
".m2ts": "video/vnd.dlna.mpeg-tts",
".m2v": "video/mpeg",
".m3u": "audio/x-mpegurl",
".m3u8": "audio/x-mpegurl",
".m4a": "audio/m4a",
".m4b": "audio/m4b",
".m4p": "audio/m4p",
".m4r": "audio/x-m4r",
".m4v": "video/x-m4v",
".mac": "image/x-macpaint",
".mak": "text/plain",
".man": "application/x-troff-man",
".manifest": "application/x-ms-manifest",
".map": "text/plain",
".master": "application/xml",
".mda": "application/msaccess",
".mdb": "application/x-msaccess",
".mde": "application/msaccess",
".mdp": "application/octet-stream",
".me": "application/x-troff-me",
".mfp": "application/x-shockwave-flash",
".mht": "message/rfc822",
".mhtml": "message/rfc822",
".mid": "audio/mid",
".midi": "audio/mid",
".mix": "application/octet-stream",
".mk": "text/plain",
".mmf": "application/x-smaf",
".mno": "text/xml",
".mny": "application/x-msmoney",
".mod": "video/mpeg",
".mov": "video/quicktime",
".movie": "video/x-sgi-movie",
".mp2": "video/mpeg",
".mp2v": "video/mpeg",
".mp3": "audio/mpeg",
".mp4": "video/mp4",
".mp4v": "video/mp4",
".mpa": "video/mpeg",
".mpe": "video/mpeg",
".mpeg": "video/mpeg",
".mpf": "application/vnd.ms-mediapackage",
".mpg": "video/mpeg",
".mpp": "application/vnd.ms-project",
".mpv2": "video/mpeg",
".mqv": "video/quicktime",
".ms": "application/x-troff-ms",
".msi": "application/octet-stream",
".mso": "application/octet-stream",
".mts": "video/vnd.dlna.mpeg-tts",
".mtx": "application/xml",
".mvb": "application/x-msmediaview",
".mvc": "application/x-miva-compiled",
".mxp": "application/x-mmxp",
".nc": "application/x-netcdf",
".nsc": "video/x-ms-asf",
".nws": "message/rfc822",
".ocx": "application/octet-stream",
".oda": "application/oda",
".odc": "text/x-ms-odc",
".odh": "text/plain",
".odl": "text/plain",
".odp": "application/vnd.oasis.opendocument.presentation",
".ods": "application/oleobject",
".odt": "application/vnd.oasis.opendocument.text",
".one": "application/onenote",
".onea": "application/onenote",
".onepkg": "application/onenote",
".onetmp": "application/onenote",
".onetoc": "application/onenote",
".onetoc2": "application/onenote",
".orderedtest": "application/xml",
".osdx": "application/opensearchdescription+xml",
".p10": "application/pkcs10",
".p12": "application/x-pkcs12",
".p7b": "application/x-pkcs7-certificates",
".p7c": "application/pkcs7-mime",
".p7m": "application/pkcs7-mime",
".p7r": "application/x-pkcs7-certreqresp",
".p7s": "application/pkcs7-signature",
".pbm": "image/x-portable-bitmap",
".pcast": "application/x-podcast",
".pct": "image/pict",
".pcx": "application/octet-stream",
".pcz": "application/octet-stream",
".pdf": "application/pdf",
".pfb": "application/octet-stream",
".pfm": "application/octet-stream",
".pfx": "application/x-pkcs12",
".pgm": "image/x-portable-graymap",
".pic": "image/pict",
".pict": "image/pict",
".pkgdef": "text/plain",
".pkgundef": "text/plain",
".pko": "application/vnd.ms-pki.pko",
".pls": "audio/scpls",
".pma": "application/x-perfmon",
".pmc": "application/x-perfmon",
".pml": "application/x-perfmon",
".pmr": "application/x-perfmon",
".pmw": "application/x-perfmon",
".png": "image/png",
".pnm": "image/x-portable-anymap",
".pnt": "image/x-macpaint",
".pntg": "image/x-macpaint",
".pnz": "image/png",
".pot": "application/vnd.ms-powerpoint",
".potm": "application/vnd.ms-powerpoint.template.macroEnabled.12",
".potx": "application/vnd.openxmlformats-officedocument.presentationml.template",
".ppa": "application/vnd.ms-powerpoint",
".ppam": "application/vnd.ms-powerpoint.addin.macroEnabled.12",
".ppm": "image/x-portable-pixmap",
".pps": "application/vnd.ms-powerpoint",
".ppsm": "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
".ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
".ppt": "application/vnd.ms-powerpoint",
".pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".prf": "application/pics-rules",
".prm": "application/octet-stream",
".prx": "application/octet-stream",
".ps": "application/postscript",
".psc1": "application/PowerShell",
".psd": "application/octet-stream",
".psess": "application/xml",
".psm": "application/octet-stream",
".psp": "application/octet-stream",
".pub": "application/x-mspublisher",
".pwz": "application/vnd.ms-powerpoint",
".qht": "text/x-html-insertion",
".qhtm": "text/x-html-insertion",
".qt": "video/quicktime",
".qti": "image/x-quicktime",
".qtif": "image/x-quicktime",
".qtl": "application/x-quicktimeplayer",
".qxd": "application/octet-stream",
".ra": "audio/x-pn-realaudio",
".ram": "audio/x-pn-realaudio",
".rar": "application/octet-stream",
".ras": "image/x-cmu-raster",
".rat": "application/rat-file",
".rc": "text/plain",
".rc2": "text/plain",
".rct": "text/plain",
".rdlc": "application/xml",
".resx": "application/xml",
".rf": "image/vnd.rn-realflash",
".rgb": "image/x-rgb",
".rgs": "text/plain",
".rm": "application/vnd.rn-realmedia",
".rmi": "audio/mid",
".rmp": "application/vnd.rn-rn_music_package",
".roff": "application/x-troff",
".rpm": "audio/x-pn-realaudio-plugin",
".rqy": "text/x-ms-rqy",
".rtf": "application/rtf",
".rtx": "text/richtext",
".ruleset": "application/xml",
".s": "text/plain",
".safariextz": "application/x-safari-safariextz",
".scd": "application/x-msschedule",
".sct": "text/scriptlet",
".sd2": "audio/x-sd2",
".sdp": "application/sdp",
".sea": "application/octet-stream",
".searchConnector-ms": "application/windows-search-connector+xml",
".setpay": "application/set-payment-initiation",
".setreg": "application/set-registration-initiation",
".settings": "application/xml",
".sgimb": "application/x-sgimb",
".sgml": "text/sgml",
".sh": "application/x-sh",
".shar": "application/x-shar",
".shtml": "text/html",
".sit": "application/x-stuffit",
".sitemap": "application/xml",
".skin": "application/xml",
".sldm": "application/vnd.ms-powerpoint.slide.macroEnabled.12",
".sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide",
".slk": "application/vnd.ms-excel",
".sln": "text/plain",
".slupkg-ms": "application/x-ms-license",
".smd": "audio/x-smd",
".smi": "application/octet-stream",
".smx": "audio/x-smd",
".smz": "audio/x-smd",
".snd": "audio/basic",
".snippet": "application/xml",
".snp": "application/octet-stream",
".sol": "text/plain",
".sor": "text/plain",
".spc": "application/x-pkcs7-certificates",
".spl": "application/futuresplash",
".src": "application/x-wais-source",
".srf": "text/plain",
".SSISDeploymentManifest": "text/xml",
".ssm": "application/streamingmedia",
".sst": "application/vnd.ms-pki.certstore",
".stl": "application/vnd.ms-pki.stl",
".sv4cpio": "application/x-sv4cpio",
".sv4crc": "application/x-sv4crc",
".svc": "application/xml",
".swf": "application/x-shockwave-flash",
".t": "application/x-troff",
".tar": "application/x-tar",
".tcl": "application/x-tcl",
".testrunconfig": "application/xml",
".testsettings": "application/xml",
".tex": "application/x-tex",
".texi": "application/x-texinfo",
".texinfo": "application/x-texinfo",
".tgz": "application/x-compressed",
".thmx": "application/vnd.ms-officetheme",
".thn": "application/octet-stream",
".tif": "image/tiff",
".tiff": "image/tiff",
".tlh": "text/plain",
".tli": "text/plain",
".toc": "application/octet-stream",
".tr": "application/x-troff",
".trm": "application/x-msterminal",
".trx": "application/xml",
".ts": "video/vnd.dlna.mpeg-tts",
".tsv": "text/tab-separated-values",
".ttf": "application/octet-stream",
".tts": "video/vnd.dlna.mpeg-tts",
".txt": "text/plain",
".u32": "application/octet-stream",
".uls": "text/iuls",
".user": "text/plain",
".ustar": "application/x-ustar",
".vb": "text/plain",
".vbdproj": "text/plain",
".vbk": "video/mpeg",
".vbproj": "text/plain",
".vbs": "text/vbscript",
".vcf": "text/x-vcard",
".vcproj": "Application/xml",
".vcs": "text/plain",
".vcxproj": "Application/xml",
".vddproj": "text/plain",
".vdp": "text/plain",
".vdproj": "text/plain",
".vdx": "application/vnd.ms-visio.viewer",
".vml": "text/xml",
".vscontent": "application/xml",
".vsct": "text/xml",
".vsd": "application/vnd.visio",
".vsi": "application/ms-vsi",
".vsix": "application/vsix",
".vsixlangpack": "text/xml",
".vsixmanifest": "text/xml",
".vsmdi": "application/xml",
".vspscc": "text/plain",
".vss": "application/vnd.visio",
".vsscc": "text/plain",
".vssettings": "text/xml",
".vssscc": "text/plain",
".vst": "application/vnd.visio",
".vstemplate": "text/xml",
".vsto": "application/x-ms-vsto",
".vsw": "application/vnd.visio",
".vsx": "application/vnd.visio",
".vtx": "application/vnd.visio",
".wav": "audio/wav",
".wave": "audio/wav",
".wax": "audio/x-ms-wax",
".wbk": "application/msword",
".wbmp": "image/vnd.wap.wbmp",
".wcm": "application/vnd.ms-works",
".wdb": "application/vnd.ms-works",
".wdp": "image/vnd.ms-photo",
".webarchive": "application/x-safari-webarchive",
".webtest": "application/xml",
".wiq": "application/xml",
".wiz": "application/msword",
".wks": "application/vnd.ms-works",
".WLMP": "application/wlmoviemaker",
".wlpginstall": "application/x-wlpg-detect",
".wlpginstall3": "application/x-wlpg3-detect",
".wm": "video/x-ms-wm",
".wma": "audio/x-ms-wma",
".wmd": "application/x-ms-wmd",
".wmf": "application/x-msmetafile",
".wml": "text/vnd.wap.wml",
".wmlc": "application/vnd.wap.wmlc",
".wmls": "text/vnd.wap.wmlscript",
".wmlsc": "application/vnd.wap.wmlscriptc",
".wmp": "video/x-ms-wmp",
".wmv": "video/x-ms-wmv",
".wmx": "video/x-ms-wmx",
".wmz": "application/x-ms-wmz",
".wpl": "application/vnd.ms-wpl",
".wps": "application/vnd.ms-works",
".wri": "application/x-mswrite",
".wrl": "x-world/x-vrml",
".wrz": "x-world/x-vrml",
".wsc": "text/scriptlet",
".wsdl": "text/xml",
".wvx": "video/x-ms-wvx",
".x": "application/directx",
".xaf": "x-world/x-vrml",
".xaml": "application/xaml+xml",
".xap": "application/x-silverlight-app",
".xbap": "application/x-ms-xbap",
".xbm": "image/x-xbitmap",
".xdr": "text/plain",
".xht": "application/xhtml+xml",
".xhtml": "application/xhtml+xml",
".xla": "application/vnd.ms-excel",
".xlam": "application/vnd.ms-excel.addin.macroEnabled.12",
".xlc": "application/vnd.ms-excel",
".xld": "application/vnd.ms-excel",
".xlk": "application/vnd.ms-excel",
".xll": "application/vnd.ms-excel",
".xlm": "application/vnd.ms-excel",
".xls": "application/vnd.ms-excel",
".xlsb": "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
".xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".xlt": "application/vnd.ms-excel",
".xltm": "application/vnd.ms-excel.template.macroEnabled.12",
".xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
".xlw": "application/vnd.ms-excel",
".xml": "text/xml",
".xmta": "application/xml",
".xof": "x-world/x-vrml",
".XOML": "text/plain",
".xpm": "image/x-xpixmap",
".xps": "application/vnd.ms-xpsdocument",
".xrm-ms": "text/xml",
".xsc": "application/xml",
".xsd": "text/xml",
".xsf": "text/xml",
".xsl": "text/xml",
".xslt": "text/xml",
".xsn": "application/octet-stream",
".xss": "application/xml",
".xtp": "application/octet-stream",
".xwd": "image/x-xwindowdump",
".z": "application/x-compress",
".zip": "application/x-zip-compressed"
}

5

Um den Beitrag umfassender zu gestalten, gibt es für .NET Core- Entwickler die FileExtensionContentTypeProvider- Klasse, die die offiziellen MIME-Inhaltstypen abdeckt .

Es funktioniert hinter den Kulissen - legt ContentType in den HTTP-Antwortheadern basierend auf der Dateinamenerweiterung fest.

Wenn Sie spezielle MIME-Typen benötigen, lesen Sie das Beispiel zum Anpassen der MIME-Typen :

public void Configure(IApplicationBuilder app)
{
    // Set up custom content types -associating file extension to MIME type
    var provider = new FileExtensionContentTypeProvider();
    // Add new mappings
    provider.Mappings[".myapp"] = "application/x-msdownload";
    provider.Mappings[".htm3"] = "text/html";
    provider.Mappings[".image"] = "image/png";
    // Replace an existing mapping
    provider.Mappings[".rtf"] = "application/x-msdownload";
    // Remove MP4 videos.
    provider.Mappings.Remove(".mp4");

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages"),
        ContentTypeProvider = provider
    });

    app.UseDirectoryBrowser(new DirectoryBrowserOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages")
    });
}

1
Vielen Dank, dass Sie uns dies mitgeteilt haben. Nur ein Tipp für Sie: Um den Stammordner Ihrer Web-App zu erhalten, sollten Sie _hostingEnvironment.WebRootPath verwenden - siehe hier
Sven

4

Die meisten Lösungen funktionieren, aber warum sollten wir uns so anstrengen, während wir auch sehr leicht MIME-Typen bekommen können? In der System.Web-Assembly gibt es eine Methode zum Abrufen des MIME-Typs aus dem Dateinamen. z.B:

string mimeType = MimeMapping.GetMimeMapping(filename);

7
Die gleiche Antwort wurde vor 3 Jahren auf dieser Seite gegeben. stackoverflow.com/a/14108040/315445
Null Head

2

Inspiriert von Samuels Antwort schrieb ich eine verbesserte Version:

  • Funktioniert auch, wenn die Erweiterung in Großbuchstaben geschrieben ist.
  • Nehmen Sie den Dateinamen als Eingabe und behandeln Sie Dateien ohne Erweiterungen ordnungsgemäß.
  • Fügen Sie nicht "." in Schlüsseln.
  • Liste von Apache , für die ich ein kleines Transformationsskript geschrieben habe .

Der resultierende Quellcode besteht aus mehr als 30.000 Zeichen, daher kann ich ihn hier nicht veröffentlichen. Überprüfen Sie ihn auf Github .


2

** Verwenden Sie die MediaTypeNames-Klasse -> Beispiel: MediaTypeNames.Application.Pdf ** Geben Sie hier die Bildbeschreibung ein


1
Während MediaTypeNameses praktisch sein kann, wenn Sie keine magischen Zeichenfolgen möchten, wenn Sie etwas von der Web-API zurückgeben, HttpResponseMessageist es tatsächlich umgekehrt zu dem, was OP verlangt.
Nrodic

1

Sie können die von Apache bereitgestellte Tabelle verwenden httpd . Es sollte trivial sein, dies einer Funktion, einem Wörterbuch, einer Liste usw. zuzuordnen.

Wie hier zu sehen ist , ist der Typ extension-> mime nicht unbedingt eine Funktion. Es kann mehrere gängige MIME-Typen pro Dateierweiterung geben. Sie sollten sich daher die Anforderungen Ihrer Anwendung ansehen und herausfinden, warum Sie sich für MIME-Typen interessieren, was Sie mit ihnen "tun" möchten usw. Können Sie Dateierweiterungen zum Schlüsseln verwenden? das gleiche Verhalten? Müssen Sie die ersten Bytes einer Datei lesen, um auch ihren MIME-Typ zu bestimmen?


1

Verwenden Sie das MimeTypeMap-Paket, das eine umfangreiche bidirektionale Zuordnung von Dateierweiterungen zu MIME-Typen und MIME-Typen zu Dateierweiterungen bietet

Verwenden von MimeTypes;

Den MIME-Typ zu einer Erweiterung bringen

Console.WriteLine("txt -> " + MimeTypeMap.GetMimeType("txt"));  // "text/plain"

Die Erweiterung auf einen MIME-Typ bringen

Console.WriteLine("audio/wav -> " + MimeTypeMap.GetExtension("audio/wav")); // ".wav"

GitHub-URL: https://github.com/samuelneff/MimeTypeMap


0

Wenn Sie keine zusätzlichen Abhängigkeiten hinzufügen möchten und dennoch versionunabhängige Anforderungen wünschen, können Sie diese Antwort zum Abrufen des MIME-Typs in verschiedenen .NET-Versionen mit dieser Antwort zu bedingten Builds für mehrere .NET Framework-Versionen mischen .

Als erstes habe ich meine Projektdatei bearbeitet. Nach der letzten Build-Definition habe ich die Eigenschaftsgruppe wie in der zweiten Antwort angegeben hinzugefügt:

<PropertyGroup>
    <DefineConstants Condition=" !$(DefineConstants.Contains(';NET')) ">$(DefineConstants);$(TargetFrameworkVersion.Replace("v", "NET").Replace(".", ""))</DefineConstants>
    <DefineConstants Condition=" $(DefineConstants.Contains(';NET')) ">$(DefineConstants.Remove($(DefineConstants.LastIndexOf(";NET"))));$(TargetFrameworkVersion.Replace("v", "NET").Replace(".", ""))</DefineConstants>
</PropertyGroup>

Jetzt habe ich eine andere Implementierung für die MimeExtensionHelpererste Antwort bereitgestellt , eine zusätzliche für alle Clients ab .NET 4.5 oder höher, die einfach Folgendes aufruft System.Web.MimeMapping.GetMimeMapping:

#if (NET10 || NET11 || NET20 || NET30 || NET35)
public static class MimeExtensionHelper
{
    static object locker = new object();
    static MethodInfo getMimeMappingMethodInfo;

    static MimeExtensionHelper()
    {
        Type mimeMappingType = Assembly.GetAssembly(typeof(HttpRuntime)).GetType("System.Web.MimeMapping");

        if (mimeMappingType == null)
            throw new SystemException("Couldnt find MimeMapping type");

        ConstructorInfo constructorInfo = mimeMappingType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);

        if (constructorInfo == null)
            throw new SystemException("Couldnt find default constructor for MimeMapping");

        mimeMapping = constructorInfo.Invoke(null);

        if (mimeMapping == null)
            throw new SystemException("Couldnt find MimeMapping");

        getMimeMappingMethodInfo = mimeMappingType.GetMethod("GetMimeMapping", BindingFlags.Static | BindingFlags.NonPublic);

        if (getMimeMappingMethodInfo == null)
            throw new SystemException("Couldnt find GetMimeMapping method");

        if (getMimeMappingMethodInfo.ReturnType != typeof(string))
            throw new SystemException("GetMimeMapping method has invalid return type");

        if (getMimeMappingMethodInfo.GetParameters().Length != 1 && getMimeMappingMethodInfo.GetParameters()[0].ParameterType != typeof(string))
            throw new SystemException("GetMimeMapping method has invalid parameters");
    }

    public static string GetMimeType(string fileName)
    {
        lock (locker)
        {
            return (string)getMimeMappingMethodInfo.Invoke(null, new object[] { fileName });
        }
    }
}
#elif NET40
public static class MimeExtensionHelper
{
    static object locker = new object();
    static MethodInfo getMimeMappingMethodInfo;

    static MimeExtensionHelper()
    {
        Type mimeMappingType = Assembly.GetAssembly(typeof(HttpRuntime)).GetType("System.Web.MimeMapping");

        if (mimeMappingType == null)
            throw new SystemException("Couldnt find MimeMapping type");           

        getMimeMappingMethodInfo = mimeMappingType.GetMethod("GetMimeMapping", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        if (getMimeMappingMethodInfo == null)
            throw new SystemException("Couldnt find GetMimeMapping method");

        if (getMimeMappingMethodInfo.ReturnType != typeof(string))
            throw new SystemException("GetMimeMapping method has invalid return type");

        if (getMimeMappingMethodInfo.GetParameters().Length != 1 && getMimeMappingMethodInfo.GetParameters()[0].ParameterType != typeof(string))
            throw new SystemException("GetMimeMapping method has invalid parameters");
    }

    public static string GetMimeType(string fileName)
    {
        lock (locker)
        {
            return (string)getMimeMappingMethodInfo.Invoke(null, new object[] { fileName });
        }
    }
}
#else // .NET 4.5 or later
public static class MimeExtensionHelper
{
    public static string GetMimeType(string fileName)
    {
        return MimeMapping.GetMimeMapping(fileName);
    }
}
#endif

Auch in den Versionen vor .NET 4.5 MimeMappinghostet die statische Klasse eine statische Instanz namens _mappingDictionary(vom Typ MimeMapping.MimeMappingDictionaryBase), die Sie von Reflection anfordern können, um neue MIME-Typen hinzuzufügen, die möglicherweise noch nicht unterstützt werden.


0

Es ist immer nicht erforderlich, dass der durch die Erweiterung der Datei berechnete MIME-Typ immer richtig ist.

Nehmen wir an, ich kann eine Datei mit der Erweiterung .png speichern, aber das Dateiformat kann ich als "ImageFormat.jpeg" festlegen.

In diesem Fall liefert die Datei, die Sie berechnen, ein anderes Ergebnis. Dies kann zu einer großen Datei führen als das Original.

Wenn Sie mit Bildern arbeiten, können Sie imagecodecInfo und ImageFormat verwenden.


0

Der obige Beitrag von Bryan Denny funktioniert bei mir nicht, da nicht alle Erweiterungen einen Unterschlüssel "Inhaltstyp" in der Registrierung haben. Ich musste den Code wie folgt anpassen:

private string GetMimeType(string sFileName)
{
  // Get file extension and if it is empty, return unknown
  string sExt = Path.GetExtension(sFileName);
  if (string.IsNullOrEmpty(sExt)) return "Unknown file type";

  // Default type is "EXT File"
  string mimeType = string.Format("{0} File", sExt.ToUpper().Replace(".", ""));

  // Open the registry key for the extension under HKEY_CLASSES_ROOT and return default if it doesn't exist
  Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(sExt);
  if (regKey == null) return mimeType;

  // Get the "(Default)" value and re-open the key for that value
  string sSubType = regKey.GetValue("").ToString();
  regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(sSubType);

  // If it exists, get the "(Default)" value of the new key
  if (regKey?.GetValue("") != null) mimeType = regKey.GetValue("").ToString();

  // Return the value
  return mimeType;
}

Jetzt funktioniert es für mich gut für alle registrierten Dateitypen und nicht registrierten oder generischen Dateitypen (wie JPG usw.).


0

Ich habe eine Liste seriöser Quellen für MIME-Typ- und Inhaltstyp-Werte zusammengestellt, die (derzeit) ausschließlich über die Dateierweiterung verschlüsselt sind.

Das Nuget-Paket finden Sie hier https://www.nuget.org/packages/FTTLib.dll/

und Quelle ist hier https://github.com/brondavies/filetypetranslator/

Diese Bibliothek soll Folgendes haben:

  • Keine externen Abhängigkeiten
  • Kein Dateisystemzugriff
  • Kleiner Speicherbedarf
  • Einfache statische Methoden (keine Erweiterungsmethoden und keine instanziierbaren Klassen)
  • Groß- und Kleinschreibung wird nicht berücksichtigt
  • Portable - funktioniert in Anwendungen, die auf eine beliebige CLR abzielen (.NET 2.0+)

0

Diese Hilfsklasse gibt den MIME-Typ (Inhaltstyp), die Beschreibung und die Symbole für jeden Dateinamen zurück:

using Microsoft.Win32;
using System;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;

public static class Helper
{
    [DllImport("shell32.dll", CharSet = CharSet.Auto)]
    private static extern int ExtractIconEx(string lpszFile, int nIconIndex, IntPtr[] phIconLarge, IntPtr[] phIconSmall, int nIcons);

    [DllImport("user32.dll", SetLastError = true)]
    private static extern int DestroyIcon(IntPtr hIcon);

    public static string GetFileContentType(string fileName)
    {
        if (fileName == null)
        {
            throw new ArgumentNullException("fileName");
        }

        RegistryKey registryKey = null;
        try
        {
            FileInfo fileInfo = new FileInfo(fileName);

            if (string.IsNullOrEmpty(fileInfo.Extension))
            {
                return string.Empty;
            }

            string extension = fileInfo.Extension.ToLowerInvariant();

            registryKey = Registry.ClassesRoot.OpenSubKey(extension);
            if (registryKey == null)
            {
                return string.Empty;
            }

            object contentTypeObject = registryKey.GetValue("Content Type");
            if (!(contentTypeObject is string))
            {
                return string.Empty;
            }

            string contentType = (string)contentTypeObject;

            return contentType;
        }
        catch (Exception)
        {
            return null;
        }
        finally
        {
            if (registryKey != null)
            {
                registryKey.Close();
            }
        }
    }

    public static string GetFileDescription(string fileName)
    {
        if (fileName == null)
        {
            throw new ArgumentNullException("fileName");
        }

        RegistryKey registryKey1 = null;
        RegistryKey registryKey2 = null;
        try
        {
            FileInfo fileInfo = new FileInfo(fileName);

            if (string.IsNullOrEmpty(fileInfo.Extension))
            {
                return string.Empty;
            }

            string extension = fileInfo.Extension.ToLowerInvariant();

            registryKey1 = Registry.ClassesRoot.OpenSubKey(extension);
            if (registryKey1 == null)
            {
                return string.Empty;
            }

            object extensionDefaultObject = registryKey1.GetValue(null);
            if (!(extensionDefaultObject is string))
            {
                return string.Empty;
            }

            string extensionDefaultValue = (string)extensionDefaultObject;

            registryKey2 = Registry.ClassesRoot.OpenSubKey(extensionDefaultValue);
            if (registryKey2 == null)
            {
                return string.Empty;
            }

            object fileDescriptionObject = registryKey2.GetValue(null);
            if (!(fileDescriptionObject is string))
            {
                return string.Empty;
            }

            string fileDescription = (string)fileDescriptionObject;
            return fileDescription;
        }
        catch (Exception)
        {
            return null;
        }
        finally
        {
            if (registryKey2 != null)
            {
                registryKey2.Close();
            }

            if (registryKey1 != null)
            {
                registryKey1.Close();
            }
        }
    }

    public static void GetFileIcons(string fileName, out Icon smallIcon, out Icon largeIcon)
    {
        if (fileName == null)
        {
            throw new ArgumentNullException("fileName");
        }

        smallIcon = null;
        largeIcon = null;

        RegistryKey registryKey1 = null;
        RegistryKey registryKey2 = null;
        try
        {
            FileInfo fileInfo = new FileInfo(fileName);

            if (string.IsNullOrEmpty(fileInfo.Extension))
            {
                return;
            }

            string extension = fileInfo.Extension.ToLowerInvariant();

            registryKey1 = Registry.ClassesRoot.OpenSubKey(extension);
            if (registryKey1 == null)
            {
                return;
            }

            object extensionDefaultObject = registryKey1.GetValue(null);
            if (!(extensionDefaultObject is string))
            {
                return;
            }

            string defaultIconKeyName = string.Format("{0}\\DefaultIcon", extensionDefaultObject);

            registryKey2 = Registry.ClassesRoot.OpenSubKey(defaultIconKeyName);
            if (registryKey2 == null)
            {
                return;
            }

            object defaultIconPathObject = registryKey2.GetValue(null);
            if (!(defaultIconPathObject is string))
            {
                return;
            }

            string defaultIconPath = (string)defaultIconPathObject;
            if (string.IsNullOrWhiteSpace(defaultIconPath))
            {
                return;
            }

            string iconfileName = null;
            int iconIndex = 0;

            int commaIndex = defaultIconPath.IndexOf(",");
            if (commaIndex > 0)
            {
                iconfileName = defaultIconPath.Substring(0, commaIndex);
                string iconIndexString = defaultIconPath.Substring(commaIndex + 1);

                if (!int.TryParse(iconIndexString, out iconIndex))
                {
                    iconIndex = 0;
                }
            }
            else
            {
                iconfileName = defaultIconPath;
                iconIndex = 0;
            }

            IntPtr[] phiconSmall = new IntPtr[1] { IntPtr.Zero };
            IntPtr[] phiconLarge = new IntPtr[1] { IntPtr.Zero };

            int readIconCount = ExtractIconEx(iconfileName, iconIndex, phiconLarge, phiconSmall, 1);

            if (readIconCount < 0)
            {
                return;
            }

            if (phiconSmall[0] != IntPtr.Zero)
            {
                smallIcon = (Icon)Icon.FromHandle(phiconSmall[0]).Clone();
                DestroyIcon(phiconSmall[0]);
            }

            if (phiconLarge[0] != IntPtr.Zero)
            {
                largeIcon = (Icon)Icon.FromHandle(phiconLarge[0]).Clone();
                DestroyIcon(phiconLarge[0]);
            }

            return;
        }
        finally
        {
            if (registryKey2 != null)
            {
                registryKey2.Close();
            }

            if (registryKey1 != null)
            {
                registryKey1.Close();
            }
        }
    }
}

Verwendung :

string fileName = "NotExists.txt";
string contentType = Helper.GetFileContentType(fileName); // "text/plain"
string description = Helper.GetFileDescription(fileName); // "Text Document"
Icon smallIcon, largeIcon;
Helper.GetFileIcons(fileName, out smallIcon, out largeIcon); // 16x16, 32x32 icons

0

Wenn ich diese Mimetypen anhand der Apache-Liste betrachte, erhalten Sie im folgenden Skript ein Wörterbuch mit allen Mimetypen.

var mimeTypeListUrl = "http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types";
var webClient = new WebClient();
var rawData = webClient.DownloadString(mimeTypeListUrl).Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);

var extensionToMimeType = new Dictionary<string, string>();
var mimeTypeToExtension = new Dictionary<string, string[]>();

foreach (var row in rawData)
{
    if (row.StartsWith("#")) continue;

    var rowData = row.Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
    if (rowData.Length != 2) continue;

    var extensions = rowData[1].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
    if (!mimeTypeToExtension.ContainsKey(rowData[0]))
    {
        mimeTypeToExtension.Add(rowData[0], extensions);
    }

    foreach (var extension in extensions)
    {
        if (!extensionToMimeType.ContainsKey(extension))
        {
            extensionToMimeType.Add(extension, rowData[0]);
        }
    }

}

-3

FileExtensionBehandle die Dateierweiterung und nicht die Mime. Der Benutzer kann die Dateierweiterung ändern. Überprüfen Sie daher die Mime. Die Codebeispiele ordnen Mime nach Dateierweiterung zu. Dies ist falsch und funktioniert nicht.

Sie müssen die contenttypeDatei abrufen und prüfen, ob die Tabelle contetTypediese Datei gemäß der Dateierweiterung mimt. Wie bekomme ich ContentTypedie Datei?

Die Verwendung von FileUpload ist also: FileUpload.PostedFile.ContentType; Wenn ich die Datei bereits habe, wie hat Ihr ContentType abgefangen?

Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.