C# 确定文件编码格式的方法
当我们用System.IO.StreamReader读取包含汉字的txt文件时,经常会读出乱码(StreamWriater写文本文件也有类似的问题),原因很简单,就是文件的编码(encoding)和StreamReader/Writer的encoding不对应。
为了解决这个问题,我写了一个类,来取得一个文本文件的encoding,这样我们就可以创建对应的StreamReader和StreamWriter来读写,保证不会出现乱码现象。其实原理很简单,文本编辑器(比如XP自带的记事本)在生成文本文件时,如果编码格式和系统默认的编码(中文系统下默认为GB2312)不一致时,会在txt文件开头部分添加特定的“编码字节序标识(Encoding Bit Order Madk,简写为BOM)”,类似PE格式的"MZ"文件头。这样它在读取时就可以根据这个BOM来确定该文本文件生成时所使用的Encoding。这个BOM我们用记事本等程序打开默认是看不到的,但是用stream按字节读取时是可以读到的。我的这个TxtFileEncoding类就是根据这个BOM“文件头”来确定txt文件生成时用到的编码的。
-
using System;
-
-
using System.Text;
-
-
using System.IO;
-
-
namespace Farproc.Text
-
-
{
-
-
/// <summary>
-
-
/// 用于取得一个文本文件的编码方式(Encoding)。
-
-
/// </summary>
-
-
public class TxtFileEncoding
-
-
{
-
-
public TxtFileEncoding()
-
-
{
-
-
//
-
-
// TODO: 在此处添加构造函数逻辑
-
-
//
-
-
}
-
-
/// <summary>
-
-
/// 取得一个文本文件的编码方式。如果无法在文件头部找到有效的前导符,Encoding.Default将被返回。
-
-
/// </summary>
-
-
/// <param name="fileName">文件名。</param>
-
-
/// <returns></returns>
-
-
public static Encoding GetEncoding(string fileName)
-
-
{
-
-
return GetEncoding(fileName, Encoding.Default);
-
-
}
-
-
/// <summary>
-
-
/// 取得一个文本文件流的编码方式。
-
-
/// </summary>
-
-
/// <param name="stream">文本文件流。</param>
-
-
/// <returns></returns>
-
-
public static Encoding GetEncoding(FileStream stream)
-
-
{
-
-
return GetEncoding(stream, Encoding.Default);
-
-
}
-
-
?// <summary>
-
-
/// 取得一个文本文件的编码方式。
-
-
/// </summary>
-
-
/// <param name="fileName">文件名。</param>
-
-
/// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param>
-
-
/// <returns></returns>
-
-
public static Encoding GetEncoding(string fileName, Encoding defaultEncoding)
-
-
{
-
-
FileStream fs = new FileStream(fileName, FileMode.Open);
-
-
Encoding targetEncoding = GetEncoding(fs, defaultEncoding);
-
-
fs.Close();
-
-
return targetEncoding;
-
-
}
-
-
/// <summary>
-
-
/// 取得一个文本文件流的编码方式。
-
-
/// </summary>
-
-
/// <param name="stream">文本文件流。</param>
-
-
/// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param>
-
-
/// <returns></returns>
-
-
public static Encoding GetEncoding(FileStream stream, Encoding defaultEncoding)
-
-
{
-
-
Encoding targetEncoding = defaultEncoding;
-
-
if(stream != null && stream.Length >= 2)
-
-
{
-
-
//保存文件流的前4个字节
-
-
byte byte1 = 0;
-
-
byte byte2 = 0;
-
-
byte byte3 = 0;
-
-
byte byte4 = 0;
-
-
//保存当前Seek位置
-
-
long origPos = stream.Seek(0, SeekOrigin.Begin);
-
-
stream.Seek(0, SeekOrigin.Begin);
-
-
int nByte = stream.ReadByte();
-
-
byte1 = Convert.ToByte(nByte);
-
-
byte2 = Convert.ToByte(stream.ReadByte());
-
-
if(stream.Length >= 3)
-
-
{
-
-
byte3 = Convert.ToByte(stream.ReadByte());
-
-
}
-
-
if(stream.Length >= 4)
-
-
{
-
-
byte4 = Convert.ToByte(stream.ReadByte());
-
-
}
-
-
//根据文件流的前4个字节判断Encoding
-
-
//Unicode {0xFF, 0xFE};
-
-
//BE-Unicode {0xFE, 0xFF};
-
-
//UTF8 = {0xEF, 0xBB, 0xBF};
-
-
if(byte1 == 0xFE && byte2 == 0xFF)//UnicodeBe
-
-
{
-
-
targetEncoding = Encoding.BigEndianUnicode;
-
-
}
-
-
if(byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)//Unicode
-
-
{
-
-
targetEncoding = Encoding.Unicode;
-
-
}
-
-
if(byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)//UTF8
-
-
{
-
-
targetEncoding = Encoding.UTF8;
-
-
}
-
-
//恢复Seek位置
-
-
stream.Seek(origPos, SeekOrigin.Begin);
-
-
}
-
-
return targetEncoding;
-
-
}
-
-
}
-
-
}
由于在GB2312和UTF7编码都没有BOM,所以需要指定一个默认的Encoding,在找不到合法的BOM时,将返回这个Encoding。有谁知道如何区分GB2312和UTF7编码txt文件的方法,也请告诉我。
由于只是static方法,所以不用new,直接通过类名调用方法,使用起来也很简单。
-
using System;
-
-
using Farproc.Text;
-
-
using System.Text;
-
-
using System.IO;
-
-
namespace ConsoleApplication1
-
-
{
-
-
/// <summary>
-
-
/// Class1 的摘要说明。
-
-
/// </summary>
-
-
class Class1
-
-
{
-
-
/// <summary>
-
-
/// 应用程序的主入口点。
-
-
/// </summary>
-
-
[]
-
-
static void Main(string[] args)
-
-
{
-
-
//
-
-
// TODO: 在此处添加代码以启动应用程序
-
-
//
-
-
string fileName = @"e:\a.txt";
-
-
//生成一个big endian Unicode编码格式的文本文件
-
-
StreamWriter sw = new StreamWriter(fileName, false, Encoding.BigEndianUnicode);//你可以试试其他编码,比如Encoding.GetEncoding("GB2312")或UTF8
-
-
sw.Write("这是一个String");
-
-
sw.Close();
-
-
//读取
-
-
Encoding fileEncoding = TxtFileEncoding.GetEncoding(fileName, Encoding.GetEncoding("GB2312"));//取得这txt文件的编码
-
-
Console.WriteLine("这个文本文件的编码为:" fileEncoding.EncodingName);
-
-
StreamReader sr = new StreamReader(fileName, fileEncoding);//用该编码创建StreamReader
-
-
//用下面的方法虽然可以让系统自动判断文本文件的编码格式,但是我们无法取得该文本文件的编码
-
-
//sr.CurrentEncoding永远为 Unicode(UTF-8)
-
-
//StreamReader sr = new StreamReader(fileName, true);
-
-
//Console.WriteLine("这个文本文件的编码为:" sr.CurrentEncoding.EncodingName);
-
-
Console.WriteLine("这个文本文件的内容为:" sr.ReadToEnd());
-
-
sr.Close();
-
-
Console.ReadLine();
-
-
}
-
-
}
-
-
}
.NET下的string永远是Unicode的,所以只能判断txt文件的Encoding。对于byte[],只有自己知道它的Encoding才能转换为string 转换为其他编码的byte[],一个例外是把整个txt文件通过stream读入byte[]后也可以根据它的前几个字节判断Encoding,对于片断,我们就无能为力了:)
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhfeihkb
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
excel下划线不显示怎么办
PHP中文网 06-23 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
photoshop蒙版画笔没反应怎么办
PHP中文网 06-24 -
抖音国际版要用什么加速器能流畅刷Tiktok的加速器
TK小达人 08-02