photo gallery   random image from the gallery
my.firefox.extensions




[05.01.2009] 09:04 - How to get a file's Mime Type from it's file extension in C#

There is a pretty neat way to get this information directly from the windows registry, rather than having to create conditional switch statements based on the file extension or creating your own mime type lookup tables.
/// <summary>
/// Get the mime type for a file based on the extension of the file anme
/// </summary>
/// <param name='FileName'>File or full path including the file name</param>
/// <returns>Source File Mime Type</returns>
public static string GetMimeType (string FileName)
{
	string FileExtension = ((FileName.LastIndexOf('.') == -1) ? 'unknown' : FileName.Substring(FileName.LastIndexOf('.')))

	string MimeType = 'application/octet-stream';
	
	Microsoft.Win32.RegistryKey RegistryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(FileExtension)
	
	if (RegistryKey != null && RegistryKey.GetValue('Content Type') != null)
		MimeType = RegistryKey.GetValue('Content Type').ToString()
	
	return MimeType;
}