EncodingHelper.cs 2.3 KB

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