XmlReaderSettings.MaxCharactersInDocument 屬性

定義

取得或設定值,指出 XML 文件中最大可允許字元數。 零 (0) 的值表示對 XML 文件大小沒有限制。 非零值指定大小上限,以字元為單位。

public:
 property long MaxCharactersInDocument { long get(); void set(long value); };
public long MaxCharactersInDocument { get; set; }
member this.MaxCharactersInDocument : int64 with get, set
Public Property MaxCharactersInDocument As Long

屬性值

Int64

XML 文件的最大可允許字元數。 預設值是 0。

範例

下列程式碼會設定這個屬性,然後嘗試剖析大於限制的檔。 在真實世界案例中,您會將此限制設定為足以處理有效檔的值,但小到足以限制惡意檔的威脅。

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);  
}  
Dim markup As String = "<Root>Content</Root>"  

Dim settings As XmlReaderSettings = New XmlReaderSettings()  
settings.MaxCharactersInDocument = 10  

Try  
    Dim reader As XmlReader = XmlReader.Create(New StringReader(markup), settings)  
    While (reader.Read())  
    End While  
Catch ex As XmlException  
    Console.WriteLine(ex.Message)  
End Try  

此程式碼會產生下列輸出:

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

備註

零 (0) 值表示剖析檔中的字元數沒有限制。 非零值會指定可剖析的最大字元數。

檔的最大字元計數包含由展開實體產生的字元計數。

如果讀取器嘗試讀取大小超過此屬性的檔, XmlException 將會擲回 。

此屬性可讓您減輕攻擊者提交極大型 XML 檔的拒絕服務攻擊。 藉由限制檔的大小,您可以偵測攻擊並可靠地復原。

適用於