Search code examples
encodingutf-8uwpricheditbox

UWP RichEditBox saveToStream utf-8 encoding


I want to save a RichEditBox Document, so I call the loadFromStream method to load the file. But, when I try to save it with saveToStream method the text saved is not encoded in utf-8.

That's my code which saves the file : IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); richEditBox.Document.SaveToStream(TextGetOptions.None, stream);

I have to encode this document in utf-8 because the text that I want to save is a script to launch and when I launch it, that raises an error saying that characters can't be read.


Solution

  • You can get the text of the richeditbox.

    string str;
    richEditBox.Document.GetText(TextGetOptions.None, out str);
    

    Then save it with the encoding you want,

    using (StreamWriter sw = new StreamWriter(stream.AsStreamForWrite(), System.Text.Encoding.UTF8))
    {
        await sw.WriteAsync(str);
    }