using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// 用于取得一个文本文件的编码方式(Encoding)。
/// </summary>
public class TxtFileEncoder
{
public TxtFileEncoder()
{
//
// 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 >= )
{
//保存文件流的前4个字节
byte byte1 = ;
byte byte2 = ;
byte byte3 = ;
byte byte4 = ;
//保存当前Seek位置
long origPos = stream.Seek(, SeekOrigin.Begin);
stream.Seek(, SeekOrigin.Begin); int nByte = stream.ReadByte();
byte1 = Convert.ToByte(nByte);
byte2 = Convert.ToByte(stream.ReadByte());
if (stream.Length >= )
{
byte3 = Convert.ToByte(stream.ReadByte());
}
if (stream.Length >= )
{
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;
} // 新增加一个方法,解决了不带BOM的 UTF8 编码问题 /// <summary>
/// 通过给定的文件流,判断文件的编码类型
/// </summary>
/// <param name="fs">文件流</param>
/// <returns>文件的编码类型</returns>
public static System.Text.Encoding GetEncoding(Stream fs)
{
byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM
Encoding reVal = Encoding.Default; BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
byte[] ss = r.ReadBytes();
if (ss[] == 0xFE && ss[] == 0xFF && ss[] == 0x00)
{
reVal = Encoding.BigEndianUnicode;
}
else if (ss[] == 0xFF && ss[] == 0xFE && ss[] == 0x41)
{
reVal = Encoding.Unicode;
}
else
{
if (ss[] == 0xEF && ss[] == 0xBB && ss[] == 0xBF)
{
reVal = Encoding.UTF8;
}
else
{
int i;
int.TryParse(fs.Length.ToString(), out i);
ss = r.ReadBytes(i); if (IsUTF8Bytes(ss))
reVal = Encoding.UTF8;
}
}
r.Close();
return reVal; } /// <summary>
/// 判断是否是不带 BOM 的 UTF8 格式
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private static bool IsUTF8Bytes(byte[] data)
{
int charByteCounter = ;  //计算当前正分析的字符应还有的字节数
byte curByte; //当前分析的字节.
for (int i = ; i < data.Length; i++)
{
curByte = data[i];
if (charByteCounter == )
{
if (curByte >= 0x80)
{
//判断当前
while (((curByte <<= ) & 0x80) != )
{
charByteCounter++;
}
//标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 
if (charByteCounter == || charByteCounter > )
{
return false;
}
}
}
else
{
//若是UTF-8 此时第一位必须为1
if ((curByte & 0xC0) != 0x80)
{
return false;
}
charByteCounter--;
}
}
if (charByteCounter > )
{
throw new Exception("非预期的byte格式!");
}
return true;
}
}
}

C# 获取文件编码的更多相关文章

  1. Python学习笔记八:文件操作(续),文件编码与解码,函数,递归,函数式编程介绍,高阶函数

    文件操作(续) 获得文件句柄位置,f.tell(),从0开始,按字符数计数 f.read(5),读取5个字符 返回文件句柄到某位置,f.seek(0) 文件在编辑过程中改变编码,f.detech() ...

  2. nodejs 获取文件的编码方式

    使用nodejs获取文件夹内文件的编码方式:使用jschardet模块. 下面的代码还有问题,没有添加结束的语句,没有判断应该在哪执行res.send(). res.send()不能放在forEach ...

  3. Atitit.检测文本文件的编码 自动获取文件的中文编码

    Atitit.检测文本文件的编码 自动获取文件的中文编码 1 不能使用load来检测编码..1 2 使用convert来检测编码1 3 程序检测文本编码2 3.1 根据utf bom头2 3.2 检测 ...

  4. paip.enhes efis 自动获取文件的中文编码

    paip.enhes efis 自动获取文件的中文编码 ##为什么需要自动获取文件的中文编码 提高开发效率,自动获取文件的中文编码  .不需要手动设置编码...轻松的.. ##cpdetector 可 ...

  5. Java如何获取文件编码格式

    1:简单判断是UTF-8或不是UTF-8,因为一般除了UTF-8之外就是GBK,所以就设置默认为GBK.  按照给定的字符集存储文件时,在文件的最开头的三个字节中就有可能存储着编码信息,所以,基本的原 ...

  6. java实现文件编码监测(转)

    chardet是mozilla自动字符集探测算法代码的java移植.这个算法的最初作者是frank Tang,C++源代码在http://lxr.mozilla.org/mozilla/source/ ...

  7. java实现文件编码监测

    java实现文件编码监测 最近在做一个文档的翻译项目,可文档的编码不知道,听头疼的.尝试了很多方法最后发现JCharDet这个工具可以轻松解决这个问题.于是作此笔记希望日后提醒自己以及帮助又需要的人. ...

  8. 【python】中文的输出,打印,文件编码问题解决方法

    直接在python中输入中文的字符串会报编译错误SyntaxError: Non-ASCII character,因为python文件默认编码方式是ASCII.如果想要打印中文字符,有两种方式: 1. ...

  9. [译]如何定义python源文件的文件编码

    简介 这篇文章是为了介绍定义python源文件文件编码的方法.python解释器可以根据所指定的编码信息对当前文件进行解析.通常来说,这种方法可以提高解析器对Unicode编码的源文件的识别,并且支持 ...

随机推荐

  1. [10.26_P2] 最短路 (单源最短路应用)

    单源最短路问题拓展 Description 给你一张图,图上有 n 个点,m 条边,要你找到两个点,使其最短路恰好包含给定的 k 个点.输出这条最短路的长度,输入保证有解. 输入格式 第一行两个数 n ...

  2. UltraEdit mac破解版

    2018-01-17 增加18.00.0.19破解 去官网下载原载,先运行一次,再在终端里执行下面代码就可以破解完成! printf '\x31\xC0\xFF\xC0\xC3\x90' | dd s ...

  3. 性能-发挥ORACLE分区表

    ORACLE分区表发挥性能 http://www.cnblogs.com/zwl715/p/3962837.html 1.1 分区表PARTITION table 在ORACLE里如果遇到特别大的表, ...

  4. Net4.6 Task 异步函数 比 同步函数 慢5倍 踩坑经历

    Net4.6 Task 异步函数 比 同步函数 慢5倍 踩坑经历 https://www.cnblogs.com/shuxiaolong/p/DotNet_Task_BUG.html 异步Task简单 ...

  5. Ubuntu midi 播放

    One of the simplest methods to play a midi file in Ubuntu is to install timidity. sudo apt-get insta ...

  6. 关于MYSQL编辑乱码问题

    今天在SQLyog中编写表数据时突然出现一个bug,在此记录分享一下. 使用MySQL数据库时,讲中文插入到数据苦衷进行刷新后全部都变成了乱码问号,如下图中studentName列: 产生乱码是因为没 ...

  7. mac下安装ngnix以及开启关闭重启

    一.安装 执行如下命令 brew search nginx brew install nginx 安装完以后,可以在终端输出的信息里看到一些配置路径: /usr/local/etc/nginx/ngi ...

  8. 原生javascript之实战 轮播图

    成品效果如下图所示: 因为博客园限制图片上传大小被我删了一些帧数,所以图片看起来会有一点卡,现实运行是不会的 搭建HTML和CSS结构 HTML代码如下: <div class="wr ...

  9. mqtt遇到的问题锦集

    1.无效客户机标识 (2) Connect指令中的KeepAlive有效范围[60秒,300秒],否则会拒绝连接. 2.消息回调出现频繁的断开连接 待解决 3.长时间消息回调出现 已断开连接 (321 ...

  10. _bzoj1798 [Ahoi2009]Seq 维护序列seq【线段树 lazy tag】

    传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1798 注意,应保证当前节点维护的值是正确的,lazy tag只是一个下传标记,在下传时应即时 ...