2

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

1 Answers1

2

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))
Community
  • 1
  • 1
Romasz
  • 29,662
  • 13
  • 79
  • 154
  • Thanks for answer, but with the encoding with UTF8 I also don't have special characters like ä or ü. These are german letters. – user3493797 Apr 03 '14 at 14:39
  • @user3493797 Have you tried also `System.Text.Encoding.Unicode`? – Romasz Apr 03 '14 at 14:46
  • @user3493797 In Silverlight there is only UTF-8 and Unicode, if you need more, you can make class with your Encoding with a little help from [this program](http://www.hardcodet.net/2010/03/silverlight-text-encoding-class-generator). – Romasz Apr 03 '14 at 14:53
  • When I tried Unicode the TextBlock is empty, so there shows no Text. – user3493797 Apr 03 '14 at 14:57
  • If the program hadn't helped - is there a chance that you can put your file.txt somewhere (or maybe better - simple app)? – Romasz Apr 03 '14 at 15:02
  • This program is awesome, but is there any documentation how can I use this class? – user3493797 Apr 03 '14 at 20:12
  • @user3493797 I've edited a little answer - I've not tried it, then give me a sign if it worked. – Romasz Apr 03 '14 at 20:24