C#使用StreamReader帮助阅读外来字符 [英] C# Help reading foreign characters using StreamReader
问题描述
我使用下面的代码来读取包含外来字符的文本文件,该文件被编码为ANSI,并且在记事本中看起来很好。下面的代码不起作用,当文件值被读取并在datagrid中显示时,字符显示为正方形,其他地方是否还有其他问题?
I'm using the code below to read a text file that contains foreign characters, the file is encoded ANSI and looks fine in notepad. The code below doesn't work, when the file values are read and shown in the datagrid the characters appear as squares, could there be another problem elsewhere?
StreamReader reader = new StreamReader(inputFilePath, System.Text.Encoding.ANSI);
using (reader = File.OpenText(inputFilePath))
谢谢
更新1 :我尝试过在 System.Text.Encoding
下找到的所有编码。并且都无法正确显示文件。
Update 1: I have tried all encodings found under System.Text.Encoding
. and all fail to show the file correctly.
更新2 :我已将文件编码(重新保存文件)更改为unicode并使用 System.Text.Encoding.Unicode
,它工作得很好。那么为什么记事本读取正确?为什么没有 System.Text.Encoding.Unicode
读取ANSI文件?
Update 2: I've changed the file encoding (resaved the file) to unicode and used System.Text.Encoding.Unicode
and it worked just fine. So why did notepad read it correctly? And why didn't System.Text.Encoding.Unicode
read the ANSI file?
推荐答案
是的,它可能与文件的实际编码,可能是unicode。尝试使用UTF-8,因为它是最常见的unicode编码形式。否则如果文件ASCII然后标准ASCII编码应该工作。
Yes, it could be with the actual encoding of the file, probably unicode. Try UTF-8 as that is the most common form of unicode encoding. Otherwise if the file ASCII then standard ASCII encoding should work.
这篇关于C#使用StreamReader帮助阅读外来字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!