我正在逐行阅读一个文件,其中包含像äåö这样的瑞典字符,但我该如何读取和保存具有瑞典字符的字符串。这是我的代码,我正在使用UTF8编码:
TextReader tr = new StreamReader(@"c:\testfile.txt", System.Text.Encoding.UTF8, true);
tr.ReadLine() //returns a string but Swedish characters are not appearing correctly...
我正在逐行阅读一个文件,其中包含像äåö这样的瑞典字符,但我该如何读取和保存具有瑞典字符的字符串。这是我的代码,我正在使用UTF8编码:
TextReader tr = new StreamReader(@"c:\testfile.txt", System.Text.Encoding.UTF8, true);
tr.ReadLine() //returns a string but Swedish characters are not appearing correctly...
您需要将System.Text.Encoding.UTF8更改为System.Text.Encoding.GetEncoding(1252)。请参见下面。
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
我自己解决了,即System.Text.Encoding.Default
将支持瑞典字符。
TextReader tr = new StreamReader(@"c:\testfile.txt", System.Text.Encoding.Default, true);
System.Text.Encoding.UTF8
应该足够了,并且它受到 .NET Framework 和 .NET Core 的支持https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding?redirectedfrom=MSDN&view=netframework-4.8
如果你仍然遇到 ��� 字符(而不是 ÅÖÄ),那么检查源文件 - 它是什么编码格式?也许是 ANSI,那么你需要转换为 UTF8。
你可以在 Notepad++ 中完成。你可以打开文本文件并转到 编码 - 转换为 UTF-8。
或者在源代码(C#)中:
var myString = Encoding.UTF8.GetString(File.ReadAllBytes(pathToTheTextFile));
tr.ReadLine()
返回的字符串无法显示瑞典字符。 - Geek