[筆記] C# 如何獲取文件的 MIME Type

MIME Type 爲什麼物:
MIME 參考手冊
svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.typeshtml

常規方式

對於有文件後綴名的,能夠使用 MimeMapping.GetMimeMapping 獲取。web

MimeMapping.GetMimeMapping(String) Method (System.Web) | Microsoft Docsapache

若是 MimeMapping.GetMimeMapping 不認識的,會返回 application/octet-stream 這個默認值。c#

其它方式

對於特定的類型的文件,能夠使用與之相關的其它方式獲取,如 Image ,能夠這樣獲取:windows

public bool TryBuildFileMimeType(string filePath, out string mimeType)
{
    if (string.IsNullOrWhiteSpace(filePath) || !System.IO.File.Exists(filePath))
    {
        mimeType = string.Empty;
        return false;
    }
    try
    {
        var image = Image.FromFile(filePath);
        mimeType = GetMimeTypeFromImage(image);
        return !string.IsNullOrWhiteSpace(mimeType);
    }
    catch (Exception ex)
    {
        mimeType = string.Empty;
        return false;
    }
}

private string GetMimeTypeFromImage(Image image)
{
    if (image.RawFormat.Equals(ImageFormat.Jpeg))
        return "image/jpeg";
    else if (image.RawFormat.Equals(ImageFormat.Bmp))
        return "image/bmp";
    else if (image.RawFormat.Equals(ImageFormat.Emf))
        return "image/emf";
    else if (image.RawFormat.Equals(ImageFormat.Exif))
        return "image/exif";
    else if (image.RawFormat.Equals(ImageFormat.Gif))
        return "image/gif";
    else if (image.RawFormat.Equals(ImageFormat.Icon))
        return "image/icon";
    else if (image.RawFormat.Equals(ImageFormat.Png))
        return "image/png";
    else if (image.RawFormat.Equals(ImageFormat.Tiff))
        return "image/tiff";
    else if (image.RawFormat.Equals(ImageFormat.Wmf))
        return "image/wmf";
    return string.Empty;
}

在我這裏的實際場景中,大部分文件都有後綴名,便可以用 MimeMapping 處理,對於沒有後綴名的,都是圖片文件,能夠用後面這種方式處理。api

固然,還能夠根據文件頭內容,先獲取文件類型,在找到對應的 MIME Type 。但這個須要本身維護一個文件頭標識的表,不知道有沒有現成的 NUGET 能夠用,求推薦。mvc

相關工具

5 Tools To Help Identify Unrecognized or Unknown File Types • Raymond.CCapp

ExifTool 這個工具很強大,能夠看不少文件元數據信息,有命令行版本和GUI版本。asp.net

ExifTool by Phil Harvey
ExifToolGUIide

其它

看到 How can I determine file type without an extension on Windows? - Super User
有個疑問,根據文件內容獲取文件的類型/MIME type,本質上是不靠譜的?只能靠猜?只是對大部分常見文件類型,有固定格式而已?

畢竟文件內容是什麼,開發者是能夠任意控制的。

參考連接或相關連接:

原文連接:
http://www.javashuo.com/article/p-khhbyslp-hp.html

相關文章
相關標籤/搜索