Geek
Geek

Reputation: 265

How to read Swedish characters properly from a txt file

I am reading a file (line by line) full of Swedish characters like äåö but how can I read and save the strings with Swedish characters. Here is my code and I am using UTF8 encoding:

TextReader tr = new StreamReader(@"c:\testfile.txt", System.Text.Encoding.UTF8, true);
tr.ReadLine() //returns a string but Swedish characters are not appearing correctly...

Upvotes: 11

Views: 12276

Answers (3)

Hawlett
Hawlett

Reputation: 914

System.Text.Encoding.UTF8 should be enough and it is supported both on .NET Framework and .NET Core https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding?redirectedfrom=MSDN&view=netframework-4.8

If you still have issues with ��� characters (instead of having ÅÖÄ) then check the source file - what kind of encoding does it have? Maybe it's ANSI, then you have to convert to UTF8.

You can do it in Notepad++. You can open text file and go to Encoding - Convert to UTF-8.

Alternatively in the source code (C#):

var myString = Encoding.UTF8.GetString(File.ReadAllBytes(pathToTheTextFile));

Upvotes: 0

Sorceri
Sorceri

Reputation: 8033

You need to change the System.Text.Encoding.UTF8 to System.Text.Encoding.GetEncoding(1252). See below

        System.IO.TextReader tr = new System.IO.StreamReader(@"c:\testfile.txt", System.Text.Encoding.GetEncoding(1252), true);
        tr.ReadLine(); //returns a string but Swedish characters are not appearing correctly

Upvotes: 19

Geek
Geek

Reputation: 265

I figured it out myself i.e System.Text.Encoding.Default will support Swedish characters.

TextReader tr = new StreamReader(@"c:\testfile.txt", System.Text.Encoding.Default, true);

Upvotes: 1

Related Questions