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"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

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

    <Grid>

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

            <FlowDocument>

                <Paragraph>

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

                </Paragraph>

                <Paragraph>

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

                </Paragraph>         

            </FlowDocument>

        </RichTextBox>

        <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>

    </Grid>

</Window>



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 );

                fStream.Close();

            }

        }