File encoding when reading a file with StreamReader

有些话、适合烂在心里 提交于 2019-12-11 05:49:45

问题


I am now having an issue where Celsius symbol gets read as C instead of °C.

Looks like the encoding the culprit. I tried to do this:

            using (StreamReader sr = new StreamReader(this._inFilePath,System.Text.Encoding.Unicode ,true))

instead of

            using (StreamReader sr = new StreamReader(this._inFilePath))

but I am now getting garbage....does the original file encoding have to match the StreamReader encoding? I am using compact framework 2.0.

I have found this online, but if use this I have read it all into a byte array, detect the end of each line,convert it to Unicode, and then proceed with a program logic. Anyone used this class?


回答1:


Yes, you need to specify the correct encoding when you construct your StreamReader. .NET might be able to detect the encoding for you. There are overloads for the StreamReader constructor which take a boolean parameter you can use to request this behavior.

public StreamReader( string path, bool detectEncodingFromByteOrderMarks)



来源:https://stackoverflow.com/questions/640242/file-encoding-when-reading-a-file-with-streamreader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!