views:

439

answers:

3

I'm given a filename and I have to be able to read it from disk and send its contents over a network. I need to be able to determine whether the file is text or binary so I know whether to use a StreamReader or BinaryReader. Another reason why I need to know the content type is because if it is binary, I have to MIME encode the data before sending it over the wire. I'd also like to be able to tell the consumer what the content type is (including the encoding if it is text).

Thanks!

+1  A: 

You either need to know the type of file ahead of time, or be told what type the file is. And why don't you just use the Stream.Write and Stream.Read methods if all you're doing is sending the file over a network? Let the consumer of the service determine the file type. You don't need to use the *Reader classes since you aren't interpreting the data on your server.

yodaj007
Due to certain constraints, I cannot send the file over the network as binary data. If it's a binary file I have to MIME encode it, if it's a text file I will send it as is. That's why I need to know the content type.
vg1890
+1  A: 

The filename extension provides your best hint at the content type of a file.

It's not perfect, but I've used the following with some success:

private static string GetContentTypeFromRegistry(string file)
{
    RegistryKey contentTypeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type");

    foreach (string keyName in contentTypeKey.GetSubKeyNames())
    {
        if (System.IO.Path.GetExtension(file).ToLower().CompareTo((string)contentTypeKey.OpenSubKey(keyName).GetValue("Extension")) == 0)
        {
            return keyName;
        }
    }

    return "unknown";
}

private static string GetFileExtensionFromRegistry(string contentType)
{
    RegistryKey contentTypeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + contentType);

    if (contentTypeKey != null)
    {
        string extension = (string)contentTypeKey.GetValue("Extension");

        if (extension != null)
        {
            return extension;
        }
    }

    return String.Empty;
}
Shawn Miller
A: 

You can try this free mime detector library out. http://www.netomatix.com/Products/DocumentManagement/MimeDetector.aspx

volatilsis