Rizo's

Get ContentType from files

by on mar.15, 2012, under Developing

I love HttpPostedFileBase! Why? Because it gives me the contenttype from files! But what about the files that I have on my disc and I need to get the ContentType? Unfortunely, you’ll either have to have a huge list with all extensions and their contenttypes which is a major pain. There’re some open source .dlls that will give you this aswell but I don’t fancy using that for such a little thing.

But I really do need to get the ContentType! So, after some searching around I found this rather comfortable way to get the ContentType without having a huge list or getting another dll to do it for me.

[sourcecode lang=”c#”]

private string GetContentType(string fileName)
{
string strcontentType = ”application/octetstream”;
string ext = Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (registryKey != null && registryKey.GetValue(”Content Type”) != null)
strcontentType = registryKey.GetValue(”Content Type”).ToString();
return strcontentType;
}
[/sourcecode]

So, what is the code above? Well.. I said it was comfortable, not the best 🙂 We do have to check the registry to get our contenttypes and that’s pretty much the same as having an entire list, the difference is that we don’t have to maintain it nor create it (if we can’t find one that has all the extensions, and then you have to think about .ppt and .pptx and so forth)

If we, for some reason, don’t get a valid contentype, we’ll just use ”application/octetstream” to return a binary contenttype.

A quick and dirty post, on a quick and dirty fix to get contenttype! 😀


22 Trackbacks / Pingbacks for this entry

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!