UPDATE: in PART 2: How to get the mime type of a file using the name of a file in C# I updated the library so it first tries to look up the mime type in a hard coded table
I recently needed to know the MIME type of a file or a file name. I know this is not that difficult certainly if you know that all the known mime types are stored in the registry of Windows. There is one caveat though, the extension you are resolving must be registered first. For example if you don’t install Adobe Acrobat PDF reader then the .pdf extension is not known and my solution I propose below won’t return any result. What you can do is either add the extension manually to the registry or install the corresponding application on the machine that needs to know about it.
Okay I’ve created a small (at least for the moment) library that allows you to call GetMimiType() on either a string or System.IO.FileInfo instance. Of course when you call this method on a string make sure the value is a valid file name! I’ve created 2 extension methods for this that can both be found in Suddenelfilio.ExtensionMethods.IO.
Here is the code to find a mime type in the registry:
string fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(fileExtension);
if (rk != null && rk.GetValue("Content Type") != null)
return rk.GetValue("Content Type").ToString();
return null;
Now if you want to use my library and its extension methods below is a sample of a console’s application Program.cs file:
using System;
using System.IO;
using Suddenelfilio.ExtensionMethods.IO;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
//Using a string with a filename as value.
string name = "d:\\test.txt";
Console.WriteLine("mimetype for file {0} is {1}", name, name.GetMimeType());
FileInfo info = new FileInfo("d:\\test.txt");
Console.WriteLine("mimetype for file {0} is {1}", info.FullName, info.GetMimeType());
Console.ReadLine();
}
}
}
The result in the console application is the following:
Here is the download containing the dll with the extension methods: Look at the follow up article


Pingback: How to get the week number for a date in C# | Suddenelfilio.net