views:

342

answers:

2

Is there a way to get a file's MIME type using some system call on Windows? I'm writing an IIS extension in C++, so it must be callable from C++, and I do have access to IIS if there is some functionality exposed. Obviously, IIS itself must be able to do this, but my googling has been unable to find out how. I did find this .net related question here on SO, but that doesn't give me much hope (as neither a good solution nor a C++ solution is mentioned there).

I need it so I can serve up dynamic files using the appropriate content type from my app. My plan is to first consult a list of MIME types within my app, then fall back to the system's MIME type listing (however that works; obviously it exists since it's how you associate files with programs). I only have a file extension to work with in some cases, but in other cases I may have an actual on-disk file to examine. Since these will not be user-uploaded files, I believe I can trust the extension and I'd prefer an extension-only lookup solution since it seems simpler and faster. Thanks!

+1  A: 

This may not help much but here is my .NET code for getting the MIME type of a file.

using System.IO;
using System.Security.Permissions;
using Microsoft.Win32;

public string GetMIMEType(string filepath)
{

    RegistryPermission regPerm = new RegistryPermission(RegistryPermissionAccess.Read, "\\\\HKEY_CLASSES_ROOT");
    RegistryKey classesRoot = Registry.ClassesRoot;

    FileInfo fi = new FileInfo(filepath);

    string dotExt = Strings.LCase(fi.Extension);

    RegistryKey typeKey = classesRoot.OpenSubKey("MIME\\Database\\Content Type");

    string keyname = null;

    foreach (var keyname in typeKey.GetSubKeyNames()) {
        RegistryKey curKey = classesRoot.OpenSubKey("MIME\\Database\\Content Type\\" + keyname);
        if (Strings.LCase(curKey.GetValue("Extension")) == dotExt) {
            //Debug.WriteLine("Content type was " & keyname)
            return keyname;
        }
    }


    return "";
}
Avitus
To clarify, this looks through the registry key `HKEY_CLASSES_ROOT\MIME\Database\Content Type` which is a 1to1 reverse mapping.. As a result, it knows that `image/jpg` has extension `.jpg`, but it doesn't know about `.jpeg` at all.
MSalters
even in .net, there isn't some pre-made library function for doing this??
rmeador
Where does Strings.LCase come from? Is this a quick port from VB.NET?
JBRWilkinson
Yep that was a quick port because I was lazy
Avitus
+1  A: 

HKCR\\.<ext>\Content Type (where "ext" is the file extension) will normally hold the MIME type.

Jerry Coffin
Unlike Avitus solution, this supports both .jpg and .jpeg
MSalters