Search code examples
c#wpfrtf

RIchTextBox Rtf encoding


I created a richtextbox in wpf where i can select text and link it to a file or resource. Let's say i want to add text something into textbox and add hyperlink to D:\cdrréper

I attach a part of the code:

_link.CommandParameter = path;
 _link.NavigateUri = new Uri(path, UriKind.Absolute);
 _link.IsEnabled = true;
using (MemoryStream ms = new MemoryStream()) {
      TextRange tr = new TextRange(_link.ContentStart, _link.ContentEnd);
      tr.Save(ms, DataFormats.Rtf);
      richTextBox.Selection.Load(ms, DataFormats.Rtf);
 }           

The current text value in richtext box after load is

{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Arial;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red0\green102\blue204;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\f2 {\ul\cf3\ltrch {\field{\*\fldinst { HYPERLINK "D:\\\\cdrr'e9per" }}{\fldrslt {something}}}}\li0\ri0\sa75\sb75\fi0\ql\par}
}
}

Hyperlink value from RTF is { HYPERLINK "D:\\cdrr'e9per" }. When i'm trying to access the path is not working because cannot be founded. é character is not encoded correctly. Do you have any suggestions about how i can fix this? Thanks for any help.


Solution

  • In the Hyperlink section is needed to have a \ before 'e9. When we load the rtf string into a TextRange we need to Load it as Xaml.

    tr.Load(ms, DataFormats.Xaml);