.NET中的文件扩展名和MIME类型问题如何解决?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (55)

我想从给定的扩展名(最好不访问物理文件)获取MIME内容类型。我已经看到了一些关于这个问题的问题,并且描述执行此操作的方法可以恢复为:

  1. 使用注册表信息
  2. 使用urlmon.dll的FindMimeFromData
  3. 使用IIS信息
  4. 滚动自己的MIME映射功能。例如,以此表为基础。

我一直在使用1号,但我意识到注册表提供的信息不一致,并取决于机器上安装的软件。一些扩展名,比如.zip,不能​​用来指定一个Content-Type。

解决方案2号强迫我在磁盘上存储文件,以便读取第一个字节,虽然速度很慢,但可能会得到很好的结果。

第三种方法是基于目录服务和所有的东西,这是我不喜欢的东西,因为我必须添加COM引用,我不确定它在IIS6和IIS7之间是否一致。另外,我不知道这种方法的性能。

最后,我不想使用我自己的表格,但如果我想要一个体面的性能和平台之间的结果的一致性(甚至单声道),最终看起来是最好的选择。

你认为有比使用我自己的桌子更好的选择,还是其他描述的方法更好?你有什么经验?

提问于
用户回答回答于

这取决于你需要什么MIME类型。一般来说,对于服务(网络应用程序,Web服务等),建议不要使用依赖于操作系统设置的MIME列表,或者如果您无法找到MIME信息,则仅作为后备。

我认为这也是MS选择在他们的System.Web.MimeMapping班级中使用常量MIME类型的原因(遗憾的是,无论出于何种原因,它都是内部的)。

包(<= .NET 3.5)

public static class MimeExtensionHelper
{
    static object locker = new object();
    static object mimeMapping;
    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(mimeMapping, new object[] { filename });
    }
}

包(.NET 4.0)

public static class MimeExtensionHelper
    {
        static object locker = new object();
        static object mimeMapping;
        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(mimeMapping, new object[] { filename });
        }
    }

.NET 4.5+

不需要包装,System.Web.MimeMapping.GetMimeMapping直接调用公共方法。

用户回答回答于

我已将所有这些方法结合到了我的实用程序库中,除了可能不是第3版。顺便说一句,no.2(urlmon.dll)不需要静态文件,它只需要一些字节,无论它们来自哪里。这是我目前的类

namespace Components
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Xml.Serialization;
    using Microsoft.Win32;

    public sealed class MimeExtensionHelper
    {
        private MimeExtensionHelper() { }

        /// <summary>Finds extension associated with specified mime type</summary>
        /// <param name="mimeType">mime type you search extension for, e.g.: "application/octet-stream"</param>
        /// <returns>most used extension, associated with provided type, e.g.: ".bin"</returns>
        public static string FindExtension(string mimeType)
        {
            return ExtensionTypes.GetExtension(mimeType);
        }

        /// <summary>Finds mime type using provided extension and/or file's binary content.</summary>
        /// <param name="file">Full file path</param>
        /// <param name="verifyFromContent">Should the file's content be examined to verify founded value.</param>
        /// <returns>mime type of file, e.g.: "application/octet-stream"</returns>
        public static string FindMime(string file,bool verifyFromContent)
        {
            string extension = Path.GetExtension(file);
            string mimeType = string.Empty;
            try
            {
                if (!String.IsNullOrEmpty(extension))
                    mimeType = ExtensionTypes.GetMimeType(extension);
                if (verifyFromContent
                    || (String.IsNullOrEmpty(mimeType) && File.Exists(file)))
                    mimeType = FindMimeByContent(file,mimeType);
            }
            catch { }
            return (mimeType ?? string.Empty).Trim();//"application/octet-stream"
        }

        /// <summary>Finds mime type for file using it's binary data.</summary>
        /// <param name="file">Full path to file.</param>
        /// <param name="proposedType">Optional. Expected file's type.</param>
        /// <returns>mime type, e.g.: "application/octet-stream"</returns>
        public static string FindMimeByContent(string file
            ,string proposedType)
        {
            FileInfo fi = new FileInfo(file);
            if (!fi.Exists)
                throw new FileNotFoundException(file);
            byte[] buf = new byte[Math.Min(4096L,fi.Length)];
            using (FileStream fs = File.OpenRead(file))
                fs.Read(buf,0,buf.Length);
            return FindMimeByData(buf,proposedType);
        }

        /// <summary>Finds mime type for binary data.</summary>
        /// <param name="dataBytes">Binary data to examine.</param>
        /// <param name="mimeProposed">Optional. Expected mime type.</param>
        /// <returns>mime type, e.g.: "application/octet-stream"</returns>
        public static string FindMimeByData(byte[] dataBytes,string mimeProposed)
        {
            if (dataBytes == null || dataBytes.Length == 0)
                throw new ArgumentNullException("dataBytes");
            string mimeRet = String.Empty;
            IntPtr outPtr = IntPtr.Zero;
            if (!String.IsNullOrEmpty(mimeProposed))
                mimeRet = mimeProposed;
            int result = FindMimeFromData(IntPtr.Zero
                ,null
                ,dataBytes
                ,dataBytes.Length
                ,String.IsNullOrEmpty(mimeProposed) ? null : mimeProposed
                ,0
                ,out outPtr
                ,0);
            if (result != 0)
                throw Marshal.GetExceptionForHR(result);
            if (outPtr != null && outPtr != IntPtr.Zero)
            {
                mimeRet = Marshal.PtrToStringUni(outPtr);
                Marshal.FreeCoTaskMem(outPtr);
            }
            return mimeRet;
        }

        [DllImport("urlmon.dll"
            ,CharSet = CharSet.Unicode
            ,ExactSpelling = true
            ,SetLastError = true)]
        static extern Int32 FindMimeFromData(IntPtr pBC
            ,[MarshalAs(UnmanagedType.LPWStr)] String pwzUrl
            ,[MarshalAs(UnmanagedType.LPArray,ArraySubType = UnmanagedType.I1,SizeParamIndex = 3)] Byte[] pBuffer
            ,Int32 cbSize
            ,[MarshalAs(UnmanagedType.LPWStr)] String pwzMimeProposed
            ,Int32 dwMimeFlags
            ,out IntPtr ppwzMimeOut
            ,Int32 dwReserved);

        private static MimeTypeCollection _extensionTypes = null;
        private static MimeTypeCollection ExtensionTypes
        {
            get
            {
                if (_extensionTypes == null)
                    _extensionTypes = new MimeTypeCollection();
                return _extensionTypes;
            }
        }

        [Serializable]
        [XmlRoot(ElementName = "mimeTypes")]
        private class MimeTypeCollection : List<MimeTypeCollection.mimeTypeInfo>
        {
            private SortedList<string,string> _extensions;
            private SortedList<string,List<string>> _mimes;

            private void Init()
            {
                if (_extensions == null || _mimes == null
                    || _extensions.Count == 0 || _mimes.Count == 0)
                {
                    _extensions = new SortedList<string,string>(StringComparer.OrdinalIgnoreCase);
                    _mimes = new SortedList<string,List<string>>(StringComparer.OrdinalIgnoreCase);
                    foreach (var mime in this)
                    {
                        _mimes.Add(mime.MimeType,new List<string>(mime.Extensions));
                        foreach (string ext in mime.Extensions)
                            if (!_extensions.ContainsKey(ext))
                                _extensions.Add(ext,mime.MimeType);
                    }
                }
            }

            public String GetExtension(string type)
            {
                Init();
                return _mimes.ContainsKey(type) ? _mimes[type][0] : string.Empty;
            }

            public String GetMimeType(string extension)
            {
                Init();
                return _extensions.ContainsKey(extension) ? _extensions[extension] : string.Empty;
            }

        public MimeTypeCollection()
        {
            this.Add(new mimeTypeInfo("application/applixware",new List<string>(new[] { ".aw" })));
            this.Add(new mimeTypeInfo("application/atom+xml",new List<string>(new[] { ".atom" })));
            // ... Whole list from apache's site
            this.Add(new mimeTypeInfo("x-x509-ca-cert",new List<string>(new[] { ".cer" })));
            try
            {
                using (RegistryKey classesRoot = Registry.ClassesRoot)
                using (RegistryKey typeKey = classesRoot.OpenSubKey(@"MIME\Database\Content Type"))
                {
                    string[] subKeyNames = typeKey.GetSubKeyNames();
                    string extension = string.Empty;
                    foreach (string keyname in subKeyNames)
                    {
                        string trimmed = (keyname ?? string.Empty).Trim();
                        if (string.IsNullOrEmpty(trimmed))
                            continue;
                        if (!String.IsNullOrEmpty(GetExtension(trimmed)))
                            continue;
                        string subKey = "MIME\\Database\\Content Type\\" + trimmed;
                        using (RegistryKey curKey = classesRoot.OpenSubKey(subKey))
                        {
                            extension = (curKey.GetValue("Extension") as string ?? string.Empty).Trim();
                            if (extension.Length > 0)
                                this.Add(new mimeTypeInfo(trimmed
                                    ,new List<string>(new[] { extension })));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.ToString();
            }
        }

        [Serializable]
        public class mimeTypeInfo
        {
            [XmlAttribute(AttributeName = "mimeType")]
            public String MimeType { get; set; }

            [XmlElement("extension")]
            public List<String> Extensions { get; set; }

            public mimeTypeInfo(string mimeType,List<string> extensions)
            {
                MimeType = mimeType;
                Extensions = extensions;
            }

            public mimeTypeInfo() { }
        }
    }
}

}

扫码关注云+社区