C#读写文件中文乱码

来源:互联网 发布:体检 知乎 编辑:程序博客网 时间:2024/06/14 14:15

读写文件的时候,文件中存在中文字符;

直接读取会出现乱码,然后一搜索网上的各种乱码处理方法,大多数是对读取的string进行转码。

其实有一种简单的方法,就是直接在读取的时候就设置编码,代码如下:

FileStream aFile = new FileStream(SingleFile,FileMode.Open);StreamReader sr = new StreamReader(aFile,Encoding.GetEncoding("gb2312"),true);string FileContent = sr.ReadToEnd();aFile.Close();
<span style="line-height: 15.4px; font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; background-color: rgb(255, 255, 255);"></span>
<span style="line-height: 15.4px; font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; background-color: rgb(255, 255, 255);">其中第二行就是设置编码了,不过记得保存的时候也要注意设置好这个编码;</span>
完成这个设置后读取中文就没有问题了。

0 0
原创粉丝点击