Search code examples
c#textwindows-phone-8streamreader

Special Characters on Windows Phone 8 with StreamReader


I want to read an txt-file with StreamReader and then give it to TextBlock. The Code is for a Windows Phone App and is in C#:

var resource = System.Windows.Application.GetResourceStream(new Uri("File.txt", UriKind.Relative));
StreamReader sreader = new StreamReader(resource.Stream);

while ((line = sreader.ReadLine()) != null)
{
   TextBlock.Text = sreader.ReadLine();
}

This read all the Text from the file to my TextBlock, but I have special characters in it, like ä or ü or ö and they don't display in the TextBlock. How can I display these characters in my TextBlock?


Solution

  • Try to define StreamReader with encoding - for example UTF8:

    using (StreamReader sreader = new StreamReader(resource.Stream, System.Text.Encoding.UTF8))
    { 
      while ((line = sreader.ReadLine()) != null)
        TextBlock.Text = sreader.ReadLine();
    }
    

    Also it's usefull to put your StreamReader into using as it is IDisposable.


    If you need other Encoding than UTF8 or Unicode, then you can try to use this program to generate the Encoding.

    Following this answer you should paste the generated code and then use it for your StreamReader (I've not tried it):

    Encoding myEncoding = new GeneratedEncoding();
    

    And then:

    using (StreamReader sreader = new StreamReader(resource.Stream, myEncoding))