在C#中獲取文件的MIME類型(Content Type)的方法如下
一.使用MimeMapping類
在System.Web程序集中,當前為靜態類,就一個獲取
// // 摘要: // 映射文檔擴展使 MIME 類型內容。 public static class MimeMapping { // // 摘要: // 返回映射為指定的文件名的 MIME。 // // 參數: // fileName: // 用於確定 MIME 類型的文件名。 public static string GetMimeMapping(string fileName); }
注:1.使用簡單
2.需要.Net Framework 4.5以上支持
3.如果沒有找到對應的MIME Type的類型則返回二進制文件的類型 :
application/octet-stream
//MimeMapping 類僅有一個方法就是獲取文件的Mime類型 //需要.Net 4.5的框架 string file = @"H:\桌面\截圖\博客截圖\dbv2.png"; string contentType = MimeMapping.GetMimeMapping(file); Console.WriteLine($"MIME Type:{contentType}");
二、使用注冊表中定義的MIME類型,查詢
string file = @"H:\桌面\截圖\博客截圖\dbv2.png"; string mimeType = "application/unknown"; string ext = Path.GetExtension(file).ToLower(); //使用注冊表中的Mime類型對應 RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(ext); if (regKey != null && regKey.GetValue("Content Type") != null) { mimeType = regKey.GetValue("Content Type").ToString(); } Console.WriteLine(mimeType);
三、可以自己定義擴展名對應的Mime類型
更多: