The content of RichTextBox can be saved to a file (or any other stream) using TextRange class. It supports following four formats:
- System.Windows.DataFormats.Text : This saves the plain text in the content of RichTextBox excluding the formatting information and the images.
- System.Windows.DataFormats.Rtf : This saves the content in RTF format preserving formating information and images.
- 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.
- 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();
Thank you so much! It was very useful for me.
It seems subscripts & superscripts are not properly saved in RTF format. Any solution for that matter?
For some reason I keep trying this but textrange keeps turning the flowdocument in the richtextbox into plain text