How to load a text file in a RichTextBox control in WPF

Soft Dev Jun 25, 2009
How to load a text file in a RichTextBox control in WPF
The following code snippet shows how to load a text file in RichTextBox (RTB). Using the same approach, you may use any file.

The XAML user interface is listed here:

<Window x:Class="RichTextBoxSample.Window1"



    Title="Window1" Height="300" Width="490">


        <RichTextBox Name="RTB" Height="167" Margin="0,0,190,95" Width="278">



                    <Run>First paragraph goes here. Type some text here.</Run>



                    <Run>Second paragraph goes here. Type some text here.</Run>




        <Button Height="36" Margin="12,0,0,34" Name="button1" VerticalAlignment="Bottom"

                HorizontalAlignment="Left" Width="97" Click="button1_Click">Get Contents</Button>

        <Button Height="32" HorizontalAlignment="Right" Margin="0,18,15,0" Name="LoadButton"

                VerticalAlignment="Top" Width="145" Click="LoadButton_Click">Load</Button>

        <Button Height="37" HorizontalAlignment="Right" Margin="0,59,15,0" Name="SaveButton"

                VerticalAlignment="Top" Width="144" Click="SaveButton_Click">Save</Button>

        <Button HorizontalAlignment="Right" Margin="0,110,13,115" Name="PrintButton"

                Width="148" Click="PrintButton_Click">Print</Button>

        <Button Height="41" Margin="130,0,215,29" Name="ClearButton" VerticalAlignment="Bottom" Click="ClearButton_Click">Clear</Button>



Here is the Load button click event handler.

private void LoadButton_Click(object sender, RoutedEventArgs e)


            string fileName = @"C:\junk\test.txt";

            TextRange range;

            FileStream fStream;

            if (File.Exists(fileName))


                range = new TextRange(RTB.Document.ContentStart, RTB.Document.ContentEnd);

                fStream = new FileStream(fileName, FileMode.OpenOrCreate);

                range.Load(fStream, DataFormats.Text );




Soft Dev
Soft Dev

Software developer working with WPF and Silverlight.