How to determine the type of file content in .NET?

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

Thanks!

+3
source share
3 answers

.

, :

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;
}
+2

, , . Stream.Write Stream.Read, , , ? . * Reader, .

+1
0
source

Source: https://habr.com/ru/post/1703046/


All Articles