Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

I'm looking for a c# code to find out proper file extension when you know content-type, but aren't sure for the file extension?

like image 378
Clack Avatar asked Dec 21 '22 14:12

Clack


2 Answers

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>

like image 173
Aurojit Panda Avatar answered Dec 29 '22 12:12

Aurojit Panda


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

like image 37
EladTal Avatar answered Dec 29 '22 12:12

EladTal