EncodingHelper.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. namespace Core.Util.Extension
  5. {
  6. public static class StreamExtension
  7. {
  8. /// <summary>
  9. /// 压入一个布尔量,当前位置提升1
  10. /// </summary>
  11. /// <param name="stream"></param>
  12. /// <param name="value"></param>
  13. /// <returns></returns>
  14. public static Stream Push(this Stream stream, bool value)
  15. {
  16. //stream.WriteArray()
  17. return stream;
  18. }
  19. }
  20. /// <summary>编码助手</summary>
  21. public static class EncodingHelper
  22. {
  23. #region 编码检测
  24. /// <summary>检测文件编码</summary>
  25. public static Encoding Detect(this string filename)
  26. {
  27. using (var fs = File.OpenRead(filename))
  28. {
  29. return Detect(fs);
  30. }
  31. }
  32. /// <summary>检测文件编码</summary>
  33. public static Encoding DetectEncoding(this FileInfo file)
  34. {
  35. using (var fs = file.OpenRead())
  36. {
  37. return fs.Detect();
  38. }
  39. }
  40. /// <summary>检测数据流编码</summary>
  41. /// <param name="stream">数据流</param>
  42. /// <param name="sampleSize">BOM检测失败时用于启发式探索的数据大小</param>
  43. /// <returns></returns>
  44. public static Encoding Detect(this Stream stream, long sampleSize = 0x400)
  45. {
  46. // 记录数据流原始位置,后面需要复原
  47. var pos = stream.Position;
  48. stream.Position = 0;
  49. // 首先检查BOM
  50. var boms = new byte[stream.Length > 4 ? 4 : stream.Length];
  51. stream.Read(boms, 0, boms.Length);
  52. var encoding = boms.Detect();
  53. if (encoding != null)
  54. {
  55. stream.Position = pos;
  56. return encoding;
  57. }
  58. // BOM检测失败,开始启发式探测
  59. // 抽查一段字节数组
  60. var data = new byte[sampleSize > stream.Length ? stream.Length : sampleSize];
  61. Array.Copy(boms, data, boms.Length);
  62. if (stream.Length > boms.Length) stream.Read(data, boms.Length, data.Length - boms.Length);
  63. stream.Position = pos;
  64. return data.DetectInternal();
  65. }
  66. #endregion
  67. }
  68. }