Search code examples
c#wpf.net-6.0richtextboxrtf

Extract RTF String from RichTextBox in C# .Net6.0 WPF


I am struggeling to get the RTF Text out of my RichTextBox. I am using C# .Net6.0, WPF.

I need to get the RTF String from the RichTextBox and store it in a variable. This Variable is in a class that generates a File where the RTF String should be in.

The RTF-String should contain all Formatting like Bold, Italic and coloured text. When the Variable is loaded back in the RichTextBox it should display all the formattings as it was when it were saved.

I know how to extract the Plain Text but not the RTF-Text. RichTextBox.Rtf is only available in WinForms. Searching the Internet gets me only to "How to get the Plain Text from a RichTextBox" but it seems no one else have this problem i have.

The variable where the RTF-String should be saved is a string. The official Microsoft Documentation isn't helpful as well.

I tried to search for a method that shows me the RTF-String from a RichTextBox. I also search in the TextRange where i get the plain text out of a RichTextBox but it seems that the TextRange only display the plain-text. I found something as TextRange.Save(stream, DataFormat.RTF) but this saved the string directly to a file instead of a variable.


Solution

  • To get the FlowDocument content in the RTF format you can use the following extension method:

    using System.IO;
    using System.Text;
    using System.Windows;
    using System.Windows.Documents;
    
    public static string RawRtf(this FlowDocument document)
    {
        using (var stream = new MemoryStream())
        {
            // Select all the document content
            var range = new TextRange(document.ContentStart, document.ContentEnd);
            // Save to a MemoryStream
            range.Save(stream, DataFormats.Rtf);
            // Convert from stream to the string 
            return Encoding.ASCII.GetString(stream.ToArray());
        }
    }
    

    Example how to call it (rtb is name of a RichTextBox):

    string rtf = rtb.Document.RawRtf();
    

    The test screenshot:

    enter image description here