内容类型扩展名

mrb*_*lah 16 c# content-type

是否有任何基于文件扩展名返回内容类型的内置函数?

Ces*_*Gon 16

从来没听说过.但是你可以使用这段代码:

using Microsoft.Win32;

RegistryKey key = Registry.ClassesRoot.OpenSubKey(extension);
string contentType = key.GetValue("Content Type").ToString();
Run Code Online (Sandbox Code Playgroud)

您需要添加额外的代码以进行错误处理.

注意:扩展名需要以点为前缀,例如.txt.

  • 有没有办法走向另一个方向?我有内容类型,我想用适当的扩展名缓存内容. (2认同)
  • @Jordan:我建议你用这个创建一个问题.人们会在那里回答. (2认同)

Mar*_*den 7

从.Net Framework 4.5开始,有一个类System.Web.MimeMapping具有完整的mime类型库,其中包含获取所请求的mime类型的方法.

请参阅:http://msdn.microsoft.com/en-us/library/system.web.mimemapping(v=vs.110).aspx

或实施GetMimeMapping:https://referencesource.microsoft.com/#System.Web/MimeMapping.cs


nay*_*kam 6

FYKI,检查\ HKEY_CLASSES_ROOT\MIME\Database\Content Type下的注册表.将有内容类型和文件扩展名列表.如果您可以通过Windows API加载此信息,那么您可以获得内容类型映射的文件扩展名.

心连心

更新:[来源] [1]

public string GetMIMEType(string filepath)
    {
        FileInfo fileInfo = new FileInfo(filepath);
        string fileExtension = fileInfo.Extension.ToLower();

        // direct mapping which is fast and ensures these extensions are found
        switch (fileExtension)
        {
            case "htm":
            case "html":
                return "text/html";
            case "js":
                return "text/javascript"; // registry may return "application/x-javascript"
        }



            // see if we can find extension info anywhere in the registry
    //Note : there is not a ContentType key under ALL the file types , check Run --> regedit , then extensions !!!

        RegistryPermission regPerm = new RegistryPermission(RegistryPermissionAccess.Read, @"\\HKEY_CLASSES_ROOT");

        // looks for extension with a content type
        RegistryKey rkContentTypes = Registry.ClassesRoot.OpenSubKey(fileExtension);
        if (rkContentTypes != null)
        {
            object key = rkContentTypes.GetValue("Content Type");
            if (key != null)
                return key.ToString().ToLower();
        }


        // looks for a content type with extension
        // Note : This would be problem if  multiple extensions associate with one content type.
        RegistryKey typeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type");

        foreach (string keyname in typeKey.GetSubKeyNames())
        {
            RegistryKey curKey = typeKey.OpenSubKey(keyname);
            if (curKey != null)
            {
                object extension = curKey.GetValue("Extension");
                if (extension != null)
                {
                    if (extension.ToString().ToLower() == fileExtension)
                    {
                        return keyname;
                    }
                }
            }
        }

        return null;
    } 
Run Code Online (Sandbox Code Playgroud)

[1]:http://www.codeproject.com/KB/dotnet/ContentType.aspx?msg = 2903389#xx2903389xxenter code here