using System; using System.IO; using System.Text; namespace Core.Util.Extension { public static class StreamExtension { /// /// 压入一个布尔量,当前位置提升1 /// /// /// /// public static Stream Push(this Stream stream, bool value) { //stream.WriteArray() return stream; } } /// 编码助手 public static class EncodingHelper { #region 编码检测 /// 检测文件编码 public static Encoding Detect(this string filename) { using (var fs = File.OpenRead(filename)) { return Detect(fs); } } /// 检测文件编码 public static Encoding DetectEncoding(this FileInfo file) { using (var fs = file.OpenRead()) { return fs.Detect(); } } /// 检测数据流编码 /// 数据流 /// BOM检测失败时用于启发式探索的数据大小 /// public static Encoding Detect(this Stream stream, long sampleSize = 0x400) { // 记录数据流原始位置,后面需要复原 var pos = stream.Position; stream.Position = 0; // 首先检查BOM var boms = new byte[stream.Length > 4 ? 4 : stream.Length]; stream.Read(boms, 0, boms.Length); var encoding = boms.Detect(); if (encoding != null) { stream.Position = pos; return encoding; } // BOM检测失败,开始启发式探测 // 抽查一段字节数组 var data = new byte[sampleSize > stream.Length ? stream.Length : sampleSize]; Array.Copy(boms, data, boms.Length); if (stream.Length > boms.Length) stream.Read(data, boms.Length, data.Length - boms.Length); stream.Position = pos; return data.DetectInternal(); } #endregion } }