Figuring out mime type?

  • Thread starter Thread starter Amil Hanish
  • Start date Start date
A

Amil Hanish

Using just a file name, or a URL, is there a way to figure out the mime type
of a file? I want to store this so later on I can stream it back via http,
but I must want to know the correct mime type.

For file names found on a disk, how could I figure out the mime type?

For URLs, without downloading entire file (sometimes big), how can I figure
out mime type?

Thanks.
 
Hi, Amil Hanish,

You can look up the content type in the registry (of the server, of course).

i.e. for a file with extension .htm look for Content Type in
HKEY_CLASSES_ROOT\.htm

public static string GetContentType(string extension)
{
string contentType = @"binary/octet-stream";
try
{
Microsoft.Win32.RegistryKey key =
Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(extension);
contentType =
key.GetValue("Content Type", @"binary/octet-stream") as string;
key.Close();
}
catch{}
return contentType;
}

Just pass the extension (including the dot).

Most likely you will have to impersonate a user with rights to read from the
registry. See the following article for details on how to do this:

http://support.microsoft.com/?kbid=306158

Hope this helps
Martin
 
As a side note, if you stream the file back using the
"attachment;file=<name>" header, the browser will show a box that allows to
choice between openig and saving the file.
When opening, the action is based on the file extension as registered on the
client computer.

If it suits your needs, the mime type is then useless...

Patrice
 
Back
Top