0

I have the following code to save a RichTextBox to RTF and instantly reload it - I have previously posted it in this question and I used it to show a problem when serialising/deserialising RTF:

    public Stream GenerateStreamFromString(string s)
    {
        MemoryStream stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(s);
        writer.Flush();
        stream.Position = 0;
        return stream;
    }

    private async void SaveAndReloadButton_Click(object sender, RoutedEventArgs e)
    {
        string data = null;
        var range = new TextRange(this.RichText.Document.ContentStart, this.RichText.Document.ContentEnd);
        using (var memoryStream = new MemoryStream())
        {
            range.Save(memoryStream, DataFormats.Rtf);
            memoryStream.Position = 0;

            using (StreamReader reader = new StreamReader(memoryStream))
            {
                data = await reader.ReadToEndAsync();
            }
        }

        // load

        var stream = GenerateStreamFromString(data);
        range = new TextRange(this.RichText.Document.ContentStart, this.RichText.Document.ContentEnd);
        range.Load(stream, DataFormats.Rtf);
    }

I am now trying to change format to DataFormats.Rtf, a format I discovered from this blog post. Now if I simply replace DataFormats.XamlPackage with DataFormats.XamlPackage in the code above, I get the following exception at the call to range.Load(...):

An exception of type 'System.ArgumentException' occurred in PresentationFramework.dll but was not handled in user code

Additional information: Unrecognized structure in data format 'XamlPackage'.

Can anyone shed some light on why this is happening?

Community
  • 1
  • 1
Gigi
  • 28,163
  • 29
  • 106
  • 188

1 Answers1

0

Well, XamlPackage is a binary format and for some reason, putting it into a string was messing it up. Working directly with the MemoryStream or with a file works fine:

    private void SaveAndReloadButton_Click(object sender, RoutedEventArgs e)
    {
        var range = new TextRange(this.RichText.Document.ContentStart, this.RichText.Document.ContentEnd);
        using (var memoryStream = new MemoryStream())
        {
            range.Save(memoryStream, DataFormats.XamlPackage);
            memoryStream.Position = 0;

            // load

            range = new TextRange(this.RichText.Document.ContentStart, this.RichText.Document.ContentEnd);
            range.Load(memoryStream, DataFormats.XamlPackage);
        }
    }
Gigi
  • 28,163
  • 29
  • 106
  • 188