替代Urlmon.dll中具有更多MIME类型的FindMimeFromData方法

时间:2013-03-08 18:13:01

标签: c# mime-types

通过Windows DLL Urlmon.dll可访问的FindMimeFromData方法能够确定存储在内存中的给定数据的MIME类型,考虑到存储此类数据的字节数组的前256个字节。

然而,在阅读其文档后,我找到了MIME Type Detection in Windows Internet Explorer,我可以在其中找到此方法能够识别的MIME类型。见list。如您所见,此方法仅限于26种MIME类型。

所以我想知道是否有人能指出我有更多MIME类型的另一种方法,或者另外一种方法/类我可以包含我认为合适的MIME类型。

4 个答案:

答案 0 :(得分:13)

  

所以我想知道是否有人能指出我的另一种方法   我会更多的MIME类型,或者另一种方法/类   能够包含我认为合适的MIME类型。

我使用Winista和URLMon的混合来检测 上传文件的实际格式..

下载Winista:http://www.netomatix.com/Products/DocumentManagement/MimeDetector.aspx

或者使用URLMon下载项目: https://github.com/MeaningOfLights/MimeDetect

Winista MIME检测

假设有人使用jpg扩展名重命名exe,您仍然可以使用二进制分析确定“真实”文件格式。它不会检测swf或flv,但几乎所有其他众所周知的格式+你可以得到一个十六进制编辑器并添加它可以检测的更多文件。

文件魔术

Winista使用XML文件“mime-type.xml”检测真实的MIME类型,该文件包含有关文件类型和用于标识内容类型的签名的信息.eg:

<!--
 !   Audio primary type
 ! -->

<mime-type name="audio/basic"
           description="uLaw/AU Audio File">
    <ext>au</ext><ext>snd</ext>
    <magic offset="0" type="byte" value="2e736e64000000"/>
</mime-type>

<mime-type name="audio/midi"
           description="Musical Instrument Digital Interface MIDI-sequention Sound">
    <ext>mid</ext><ext>midi</ext><ext>kar</ext>
    <magic offset="0" value="MThd"/>
</mime-type>

<mime-type name="audio/mpeg"
           description="MPEG Audio Stream, Layer III">
    <ext>mp3</ext><ext>mp2</ext><ext>mpga</ext>
    <magic offset="0" value="ID3"/>
</mime-type>

当Winista无法检测到真实的文件格式时,我已经使用了URLMon方法:

public class urlmonMimeDetect
{
    [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
    private extern static System.UInt32 FindMimeFromData(
        System.UInt32 pBC,
        [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
        [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
        System.UInt32 cbSize,
        [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
        System.UInt32 dwMimeFlags,
        out System.UInt32 ppwzMimeOut,
        System.UInt32 dwReserverd
    );

public string GetMimeFromFile(string filename)
{
    if (!File.Exists(filename))
        throw new FileNotFoundException(filename + " not found");

    byte[] buffer = new byte[256];
    using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
    {
        if (fs.Length >= 256)
            fs.Read(buffer, 0, 256);
        else
            fs.Read(buffer, 0, (int)fs.Length);
    }
    try
    {
        System.UInt32 mimetype;
        FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
        System.IntPtr mimeTypePtr = new IntPtr(mimetype);
        string mime = Marshal.PtrToStringUni(mimeTypePtr);
        Marshal.FreeCoTaskMem(mimeTypePtr);
        return mime;
    }
    catch (Exception e)
    {
        return "unknown/unknown";
    }
}
}

从Winista方法内部,我回到URLMon:

   public MimeType GetMimeTypeFromFile(string filePath)
    {
        sbyte[] fileData = null;
        using (FileStream srcFile = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            byte[] data = new byte[srcFile.Length];
            srcFile.Read(data, 0, (Int32)srcFile.Length);
            fileData = Winista.Mime.SupportUtil.ToSByteArray(data);
        }

        MimeType oMimeType = GetMimeType(fileData);
        if (oMimeType != null) return oMimeType;

        //We haven't found the file using Magic (eg a text/plain file)
        //so instead use URLMon to try and get the files format
        Winista.MimeDetect.URLMONMimeDetect.urlmonMimeDetect urlmonMimeDetect = new Winista.MimeDetect.URLMONMimeDetect.urlmonMimeDetect();
        string urlmonMimeType = urlmonMimeDetect.GetMimeFromFile(filePath);
        if (!string.IsNullOrEmpty(urlmonMimeType))
        {
            foreach (MimeType mimeType in types)
            {
                if (mimeType.Name == urlmonMimeType)
                {
                    return mimeType;
                }
            }
        }

        return oMimeType;
    }

Winista from netomatix。 AFAIK是一个基于2000年初开源Java项目的C#重写。享受!

您也可以使用由Paul Zahra链接的.Net 4.5 method中提到的注册表方法或this post,但Winista是最好的恕我直言。

<强>更新

对于桌面应用程序,您可能会发现WindowsAPICodePack效果更好:

using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;

private static string GetFilePropertyItemTypeTextValueFromShellFile(string filePathWithExtension)
{
   var shellFile = ShellFile.FromFilePath(filePathWithExtension);
   var prop = shellFile.Properties.GetProperty(PItemTypeTextCanonical);
   return prop.FormatForDisplay(PropertyDescriptionFormatOptions.None);
}

答案 1 :(得分:2)

有多种可能的解决方案in this SO post,至少会给你一些思考的食物。

似乎唯一真正的方法是以二进制方式读取它然后进行比较,无论MIME类型是以某种方式声明为硬编码还是依赖于机器自己的MIME类型/注册表。

答案 2 :(得分:2)

刚刚找到FileSignatures。它实际上是一个不错的选择,在面向 Linux 的应用程序上也能正常运行。

上下文

Urlmon.dll 不适合 Linux - 因此不适用于多平台应用程序。 我在 Microsoft Docs 中找到了 this article。它引用了 File Signature Database,这是一个很好的文件类型参考(在我撰写本文时为 518)。

再深入研究,我发现了这个相当不错的项目:FileSignatures nuget here。它的可扩展性也很强,例如,您可以从 filesignatures.net 获取您需要的所有类型并创建您自己的类型模型。

用法

您可以检查任何定义的类型

var format = inspector.DetermineFileFormat(stream);

if(format is Pdf) {
  // Just matches Pdf
}

if(format is OfficeOpenXml) {
  // Matches Word, Excel, Powerpoint
}

if(format is Image) {
  // Matches any image format
}

或者根据匹配的文件类型使用它带来的一些元数据

var fileFormat = _fileFormatInspector.DetermineFileFormat(stream);
var mime = fileFormat?.MediaType;

可扩展性

您可以定义任意数量的继承自 FileFormat 的类型并配置一个 FileFormatLocator 以在需要时加载它们

var assembly = typeof(CustomFileFormat).GetTypeInfo().Assembly;

// Just the formats defined in the assembly containing CustomFileFormat
var customFormats = FileFormatLocator.GetFormats(assembly);

// Formats defined in the assembly and all the defaults
var allFormats = FileFormatLocator.GetFormats(assembly, true);

project's Github 中的更多详细信息

答案 3 :(得分:0)

寻找弹性溶液数小时后。我采用了@JeremyThompson解决方案,将其调整为适用于.net core / .net 4.5框架,并将其放入nuget package中。

   //init
   var mimeTypes = new MimeTypes();

   //usage by filepath
   var mimeType1 = mimeTypes.GetMimeTypeFromFile(filePath);

   //usage by bytearray
   var mimeType2 = mimeTypes.GetMimeTypeFromFile(bytes);