Save and Load RichTextBox content in WPF

The content of RichTextBox can be saved to a file (or any other stream) using TextRange class. It supports following four formats:

  1. System.Windows.DataFormats.Text : This saves the plain text in the content of RichTextBox excluding the formatting information and the images.
  2. System.Windows.DataFormats.Rtf : This saves the content in RTF format preserving formating information and images.
  3. System.Windows.DataFormats.Xaml : This saves the content in Xaml format which is the same format used in WPF designer for specifying content for a RichTextBox. It contains formating tags but doesn’t support image.
  4. System.Windows.DataFormats.XamlPackage : This is a binary file format which packages Xaml and any images into one file.

Following table is presenting key information about above formats:

Format Binary/Text Formating Supported Images Supported
Text Text No No
Rtf Binary Yes Yes
Xaml Text Yes No
XamlPackage Binary Yes Yes

The code for saving & loading is pretty simple once who know the relevant class. Following is the code for saving content to file.

TextRange t = new TextRange(richTextBox1.Document.ContentStart,
                                    richTextBox1.Document.ContentEnd);
FileStream file = new FileStream("Sample File.xaml", FileMode.Create);
t.Save(file, System.Windows.DataFormats.XamlPackage);
file.Close();

 

 

Following snippet is for loading the content of RichTextBox from a file.

TextRange t = new TextRange(richTextBox1.Document.ContentStart,
                                richTextBox1.Document.ContentEnd);
FileStream file = new FileStream("Good File.xaml", FileMode.Open);
t.Load(file, System.Windows.DataFormats.XamlPackage);
file.Close();

4 thoughts on “Save and Load RichTextBox content in WPF

Leave a Reply

Your email address will not be published. Required fields are marked *