Export (0) Print
Expand All

XmlReaderSettings.MaxCharactersInDocument Property

Gets or sets a value indicating the maximum allowable number of characters 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.

Namespace:  System.Xml
Assembly:  System.Xml (in System.Xml.dll)

public long MaxCharactersInDocument { get; set; }

Property Value

Type: System.Int64
The maximum allowable number of characters in an XML document. The default is 0.

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.

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;
    XmlReader reader = XmlReader.Create(new StringReader(markup), settings);
    while (reader.Read()) { }
catch (XmlException ex)

This code produces the following output:

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

.NET Framework

Supported in: 4, 3.5 SP1, 3.0 SP1, 2.0 SP1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Community Additions

© 2015 Microsoft