Search code examples
c#mime-typescontent-typesystem.netformatexception

Creating a ContentType throws an FormatException


I'm working with ContentType class to parse content type (type + encoding) of a webpage.

I'm noticed that this input fails (FormatException):

text/html; charset: windows-1255

This is the code:

using System.Net.Mime;
//...
ContentType ct;
try
{
    ct = new ContentType(content_type);
}
catch (FormatException ex)
{
    return eFileType.Unknown;
}

Why it's throwing FormatException?


Solution

  • The documentation on the ContentType constructor states that it throws an FormatException if:

    contentType is in a form that cannot be parsed.

    In this case, it is because charset: is not supported, charset= is:

    var x = new ContentType("text/html; charset=windows-1255");
    

    This behavior is according to the W3C specs on content type headers, that states that a parameter must follow this format:

    parameter := attribute "=" value

    So an equals sign is the documented separator between attribute and value.