How to get correct file extension when you know content-type
12,135
Solution 1
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>
Solution 2
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
Author by
Clack
Updated on June 05, 2022Comments
-
Clack about 2 years
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?
-
Richard Marskell - Drackir about 13 yearsThis does, of course, mean that the computer the code is running on needs to know that mime-type/extension information but that should be ok.
-
irag10 over 8 yearsWell, it might be ok, but it might well not be ok. If you're a web server dealing with application-specific files, e.g. Excel, you may well have a content type that's not installed on the web server