This documentation is archived and is not being maintained.

How to: Extract the Text Content from a RichTextBox

This example shows how to extract the contents of a RichTextBox as plain text.

The following Extensible Application Markup Language (XAML) code describes a named RichTextBox control with simple content.

<RichTextBox Name="richTB">
      <Run>Paragraph 1</Run>
      <Run>Paragraph 2</Run>
      <Run>Paragraph 3</Run>

The following code implements a method that takes a RichTextBox as an argument, and returns a string representing the plain text contents of the RichTextBox.

The method creates a new TextRange from the contents of the RichTextBox, using the ContentStart and ContentEnd to indicate the range of the contents to extract. ContentStart and ContentEnd properties each return a TextPointer, and are accessible on the underlying FlowDocument that represents the contents of the RichTextBox. TextRange provides a Text property, which returns the plain text portions of the TextRange as a string.

string StringFromRichTextBox(RichTextBox rtb)
    TextRange textRange = new TextRange(
        // TextPointer to the start of content in the RichTextBox.
        // TextPointer to the end of content in the RichTextBox.

    // The Text property on a TextRange object returns a string 
    // representing the plain text content of the TextRange. 
    return textRange.Text;