How to get correct file extension when you know content-type

前端 未结 2 1447
轮回少年
轮回少年 2020-12-21 02:17

I have a byte[] containing data for a file. Array can contain data for several different filetypes like xml, jpg, html, csv, etc.

I need to save that file in disk.

相关标签:
2条回答
  • 2020-12-21 03:05

    http://cyotek.com/article/display/mime-types-and-file-extensions has a snippet for doing this, essentially looking up the extension in the registry under HKEY_CLASSES_ROOT\MIME\Database\Content Type\<mime type>

    0 讨论(0)
  • 2020-12-21 03:12

    maybe this converter code can help:

            private static ConcurrentDictionary<string, string> MimeTypeToExtension = new ConcurrentDictionary<string, string>();
        private static ConcurrentDictionary<string, string> ExtensionToMimeType = new ConcurrentDictionary<string, string>();
    
        public static string ConvertMimeTypeToExtension(string mimeType)
        {
            if (string.IsNullOrWhiteSpace(mimeType))
                throw new ArgumentNullException("mimeType");
    
            string key = string.Format(@"MIME\Database\Content Type\{0}", mimeType);
            string result;
            if (MimeTypeToExtension.TryGetValue(key, out result))
                return result;
    
            RegistryKey regKey;
            object value;
    
            regKey = Registry.ClassesRoot.OpenSubKey(key, false);
            value = regKey != null ? regKey.GetValue("Extension", null) : null;
            result = value != null ? value.ToString() : string.Empty;
    
            MimeTypeToExtension[key] = result;
            return result;
        }
    
        public static string ConvertExtensionToMimeType(string extension)
        {
    
            if (string.IsNullOrWhiteSpace(extension))
                throw new ArgumentNullException("extension");
    
            if (!extension.StartsWith("."))
                extension = "." + extension;
    
            string result;
            if (ExtensionToMimeType.TryGetValue(extension, out result))
                return result;
    
            RegistryKey regKey;
            object value;
    
            regKey = Registry.ClassesRoot.OpenSubKey(extension, false);
            value = regKey != null ? regKey.GetValue("Content Type", null) : null;
            result = value != null ? value.ToString() : string.Empty;
    
            ExtensionToMimeType[extension] = result;
            return result;
        }
    

    origin of the idea comes from here: Snippet: Mime types and file extensions

    0 讨论(0)
提交回复
热议问题