Search code examples
c#uwpricheditbox

UWP Does RichEditBox read only .rtf files?


I try to add a file content to my RichEditBox using this method :

myRichEditBox.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.None, streamFile);

And that is how I fill my streamFile variable :

public static async void openFileAsync(string pathFolder, string file)
    {
        Windows.Storage.StorageFolder folder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(pathFolder);
        System.Diagnostics.Debug.WriteLine("folder : " + folder.Path);

        Windows.Storage.StorageFile fileOpen = await folder.GetFileAsync(file);
        System.Diagnostics.Debug.WriteLine("file : " + fileOpen.Path);

        Windows.Storage.Streams.IRandomAccessStream stream = await fileOpen.OpenAsync(Windows.Storage.FileAccessMode.Read);

        streamFile = stream;
    }

I have no exception that rises but the richBoxEdit text is unreadable (characters are unreadable). I want to read txt files.

Thank you in advance for your help.


Solution

  • If you want to use Stream to read contents of the File, You can use the method Below. This will return the contents of the file as Text.

    internal async Task<string> UsingStream(StorageFile sampleFile)
    {
        IRandomAccessStream stream = await sampleFile.OpenAsync(FileAccessMode.Read);
        ulong size = stream.Size;
        string text = string.Empty;
        using (var inputStream = stream.GetInputStreamAt(0))
        {
            using (var dataReader = new DataReader(inputStream))
            {
                uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
                text = dataReader.ReadString(numBytesLoaded);
            }
        }
        return text;
    }
    

    See the Official Microsoft Documentation for Reference

    However if you want to directly load the Text instead of stream, Use Below.

    string fileText = await FileIO.ReadTextAsync(sampleFile);
    

    And then assign the data to RichEditBox like below.

    MyRichEditBox.Document.SetText(Windows.UI.Text.TextSetOptions.None, await UsingStream(sampleFile));