C# 帮助使用 StreamReader 读取外来字符 [英] C# Help reading foreign characters using StreamReader
问题描述
我正在使用下面的代码读取包含外来字符的文本文件,该文件采用 ANSI 编码,在记事本中看起来不错.下面的代码不起作用,当读取文件值并在数据网格中显示时,字符显示为正方形,其他地方会不会有其他问题?
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屋!