没有合适的资源?快使用搜索试试~ 我知道了~
本文实例讲述了C#读取中文文件出现乱码的解决方法。分享给大家供大家参考。具体分析如下: 先来看这段代码: FileStream aFile = new FileStream(SingleFile,FileMode.Open); StreamReader sr = new StreamReader(aFile,Encoding.GetEncoding(gb2312),true); string FileContent = sr.ReadToEnd(); aFile.Close(); ProcessData Pd = new ProcessData(); Pd.ProceData(FileC
资源详情
资源评论
资源推荐
C#读取中文文件出现乱码的解决方法读取中文文件出现乱码的解决方法
本文实例讲述了C#读取中文文件出现乱码的解决方法。分享给大家供大家参考。具体分析如下:
先来看这段代码:
FileStream aFile = new FileStream(SingleFile,FileMode.Open);
StreamReader sr = new StreamReader(aFile,Encoding.GetEncoding("gb2312"),true);
string FileContent = sr.ReadToEnd();
aFile.Close();
ProcessData Pd = new ProcessData();
Pd.ProceData(FileContent);
StreamReader 使用3个参数 最后一个自动检测utf-8,中文大部分是gb2312,如果不是utf-8,就用gb2312
系统自带utf 检测 ,见如下:
private void DetectEncoding()
{
if (this.byteLen >= 2)
{
this._detectEncoding = false;
bool flag = false;
if ((this.byteBuffer[0] == 0xfe) && (this.byteBuffer[1] == 0xff))
{
this.encoding = new UnicodeEncoding(true, true);
this.CompressBuffer(2);
flag = true;
}
else if ((this.byteBuffer[0] == 0xff) && (this.byteBuffer[1] == 0xfe))
{
if (((this.byteLen < 4) || (this.byteBuffer[2] != 0)) || (this.byteBuffer[3] != 0))
{
this.encoding = new UnicodeEncoding(false, true);
this.CompressBuffer(2);
flag = true;
}
else
{
this.encoding = new UTF32Encoding(false, true);
this.CompressBuffer(4);
flag = true;
}
}
else if (((this.byteLen >= 3) && (this.byteBuffer[0] == 0xef)) && ((this.byteBuffer[1] == 0xbb) && (this.byteBuffer[2] == 0xbf)))
{
this.encoding = Encoding.UTF8;
this.CompressBuffer(3);
flag = true;
}
else if ((((this.byteLen >= 4) && (this.byteBuffer[0] == 0)) && ((this.byteBuffer[1] == 0) && (this.byteBuffer[2] == 0xfe))) && (this.byteBuffer[3] == 0xff))
{
this.encoding = new UTF32Encoding(true, true);
this.CompressBuffer(4);
flag = true;
}
else if (this.byteLen == 2)
{
this._detectEncoding = true;
}
if (flag)
{
this.decoder = this.encoding.GetDecoder();
this._maxCharsPerBuffer = this.encoding.GetMaxCharCount(this.byteBuffer.Length);
this.charBuffer = new char[this._maxCharsPerBuffer];
}
}
}
希望本文所述对大家的C#程序设计有所帮助。
您可能感兴趣的文章您可能感兴趣的文章:Unity3d发布IOS9应用时出现中文乱码的解决方法Java读写txt文件时防止中文乱码问题出现的方法介绍
java 逐行读取txt文本如何解决中文乱码Android读取本地json文件的方法(解决显示乱码问题)Java读取、写入文件如何解决乱
码问题php使用fgetcsv读取csv文件出现乱码的解决方法java自动根据文件内容的编码来读取避免乱码php 读取文件乱码问题
php读取mysql中文数据出现乱码的解决方法iOS读取txt文件出现中文乱码的解决方法
weixin_38587924
- 粉丝: 4
- 资源: 992
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0