Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
MaxCharactersFromEntities Property

XmlReaderSettings.MaxCharactersFromEntities Property

Gets or sets a value indicating the maximum allowable number of characters in a document that result from expanding entities.

Namespace:  System.Xml
Assemblies:   System.Xml (in System.Xml.dll)
  System.Xml.ReaderWriter (in System.Xml.ReaderWriter.dll)

public long MaxCharactersFromEntities { get; set; }

Property Value

Type: System.Int64
The maximum allowable number of characters from expanded entities. The default is 0.

A zero (0) value means no limits on the number of characters that result from expanding entities. A non-zero value specifies the maximum number of characters that can result from expanding entities.

If the reader attempts to read a document that contains entities such that the expanded size will exceed this property, an XmlException will be thrown.

This property allows you to mitigate denial of service attacks where the attacker submits XML documents that attempt to exceed memory limits via expanding entities. By limiting the characters that result from expanded entities, you can detect the attack and recover reliably.

The following code sets this property, and then attempts to parse a document that contains an entity that expands to a size greater than the set 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 =
@"<!DOCTYPE Root [
  <!ENTITY anEntity ""Expands to more than 30 characters"">
<Root>Content &anEntity;</Root>";
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.ValidationType = ValidationType.DTD;
settings.MaxCharactersFromEntities = 30;
    XmlReader reader = XmlReader.Create(new StringReader(markup), settings);
    while (reader.Read()) { }
catch (XmlException ex)

This example produces the following output:

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

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Portable Class Library

Supported in: Portable Class Library
© 2015 Microsoft