Search This Blog

Thursday, November 21, 2013

Example: Load and save content of WPF RichTextBox to a file

WPF > Controls  > ContentControl > RichTextBox

RichTextBox operates on FlowDocument objects.

Note: Pasting HTML content into a RichTextBox might result in unexpected behavior because RichTextBox uses RTF format rather than directly using HTML format.

Examples


Example

Load and save content of WPF RichTextBox to a file


XAML:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:src="clr-namespace:WpfApplication2"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="WpfApplication2.MainWindow"
        Title="MainWindow"
       d:DesignWidth="300" d:DesignHeight="320"
        >
    <Grid HorizontalAlignment="Left" Height="295" VerticalAlignment="Top" Width="300">
        <Button x:Name="btnSave" Content="Save" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="btnSave_Click"/>
        <Button x:Name="btnLoad" Content="Load" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="80,0,0,0" Click="btnLoad_Click"/>
        <RichTextBox x:Name="rtb" HorizontalAlignment="Left" Height="267" Margin="0,27,0,0" VerticalAlignment="Top" Width="300">
            <FlowDocument>
                <Paragraph>
                    <Run Text=""/>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>
    </Grid>
</Window>

C# Code

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApplication2
{
     /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    ///

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            TextRange t = new TextRange(rtb.Document.ContentStart,rtb.Document.ContentEnd);
            FileStream file = new FileStream("c:\\rtb.xaml", FileMode.Create);
            t.Save(file, System.Windows.DataFormats.XamlPackage);
             file.Close();
        }
        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            TextRange t = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
            FileStream file = new FileStream("c:\\rtb.xaml", FileMode.Open);
            t.Load(file, System.Windows.DataFormats.XamlPackage);
            file.Close();
        }
    }
}