XmlReaderSettings.MaxCharactersInDocument Property

Definition

Gets or sets a value indicating the maximum allowable number of characters in an XML document. A zero (0) value means no limits on the size of the XML document. A non-zero value specifies the maximum size, in characters.

public long MaxCharactersInDocument { get; set; }

Property Value

The maximum allowable number of characters in an XML document. The default is 0.

Examples

The following code sets this property, and then attempts to parse a document larger than the limit. In a real world scenario, you would set this limit to a value large enough to handle valid documents, yet small enough to limit the threat from malicious documents.

string markup = "<Root>Content</Root>";

XmlReaderSettings settings = new XmlReaderSettings();
settings.MaxCharactersInDocument = 10;

try
{
    XmlReader reader = XmlReader.Create(new StringReader(markup), settings);
    while (reader.Read()) { }
}
catch (XmlException ex)
{
    Console.WriteLine(ex.Message);
}

This code produces the following output:

There is an error in XML document (MaxCharactersInDocument, ).

Remarks

A zero (0) value means no limits on the number of characters in the parsed document. A non-zero value specifies the maximum number of characters that can be parsed.

The maximum character count for the document includes the count of characters that result from expanded entities.

If the reader attempts to read a document with a size that exceeds this property, an XmlException will be thrown.

This property allows you to mitigate denial of service attacks where the attacker submits extremely large XML documents. By limiting the size of a document, you can detect the attack and recover reliably.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0