Loading

[笔记] C# 如何获取文件的 MIME Type

MIME Type 为何物:
MIME 参考手册
svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

常规方式

对于有文件后缀名的,可以使用 MimeMapping.GetMimeMapping 获取。

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

如果 MimeMapping.GetMimeMapping 不认识的,会返回 application/octet-stream 这个默认值。

其它方式

对于特定的类型的文件,可以使用与之相关的其它方式获取,如 Image ,可以这样获取:

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 处理,对于没有后缀名的,都是图片文件,可以用后面这种方式处理。

当然,还可以根据文件头内容,先获取文件类型,在找到对应的 MIME Type 。但这个需要自己维护一个文件头标识的表,不知道有没有现成的 NUGET 可以用,求推荐。

相关工具

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

ExifTool 这个工具很强大,可以看很多文件元数据信息,有命令行版本和GUI版本。

ExifTool by Phil Harvey
ExifToolGUI

其它

看到 How can I determine file type without an extension on Windows? - Super User
有个疑问,根据文件内容获取文件的类型/MIME type,本质上是不靠谱的?只能靠猜?只是对大部分常见文件类型,有固定格式而已?

毕竟文件内容是什么,开发者是可以任意控制的。

参考链接或相关链接:

原文链接:
https://www.cnblogs.com/jasongrass/p/11635454.html

posted @ 2019-10-08 15:02  J.晒太阳的猫  阅读(1861)  评论(1编辑  收藏  举报