使用StreamReader读取文件时的文件编码 [英] File encoding when reading a file with StreamReader

查看:165
本文介绍了使用StreamReader读取文件时的文件编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有一个问题,其中摄氏符号读取为C而不是°C。

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))

而不是

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

但是我现在正在得到垃圾....原始文件编码是否必须匹配StreamReader编码?我正在使用紧凑框架2.0。

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

我发现这个在线,但如果使用这个我已经将它全部读入字节数组,检测每行的结尾,将其转换为Unicode ,然后继续执行程序逻辑。任何人使用这个类?

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?

推荐答案

是的,您需要在构建StreamReader时指定正确的编码。 .NET可能能够检测到您的编码。对于StreamReader构造函数,可以使用可以用于请求此行为的布尔参数来重载StreamReader。

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)

public StreamReader( string path, bool detectEncodingFromByteOrderMarks)

这篇关于使用StreamReader读取文件时的文件编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆