CNAS取数仪器端升级
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

4 ay önce
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. namespace CnasSynchronusDAL
  8. {
  9. /// <summary>
  10. /// 读取一般性文件规则接口
  11. /// </summary>
  12. public class BaseReadFileMode
  13. {
  14. #region 得到文本的编码格式,避免因解析问题造成的乱码
  15. public static System.Text.Encoding GetType(string FILE_NAME)
  16. {
  17. FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
  18. Encoding r = GetType(fs);
  19. fs.Close();
  20. return r;
  21. }
  22. public static System.Text.Encoding GetType(FileStream fs)
  23. {
  24. byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
  25. byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
  26. byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM
  27. Encoding reVal = Encoding.Default;
  28. BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
  29. int i;
  30. int.TryParse(fs.Length.ToString(), out i);
  31. byte[] ss = r.ReadBytes(i);
  32. if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
  33. {
  34. reVal = Encoding.UTF8;
  35. }
  36. else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
  37. {
  38. reVal = Encoding.BigEndianUnicode;
  39. }
  40. else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
  41. {
  42. reVal = Encoding.Unicode;
  43. }
  44. r.Close();
  45. return reVal;
  46. }
  47. private static bool IsUTF8Bytes(byte[] data)
  48. {
  49. int charByteCounter = 1; //计算当前正分析的字符应还有的字节数
  50. byte curByte; //当前分析的字节.
  51. for (int i = 0; i < data.Length; i++)
  52. {
  53. curByte = data[i];
  54. if (charByteCounter == 1)
  55. {
  56. if (curByte >= 0x80)
  57. {
  58. //判断当前
  59. while (((curByte <<= 1) & 0x80) != 0)
  60. {
  61. charByteCounter++;
  62. }
  63. //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X
  64. if (charByteCounter == 1 || charByteCounter > 6)
  65. {
  66. return false;
  67. }
  68. }
  69. }
  70. else
  71. {
  72. //若是UTF-8 此时第一位必须为1
  73. if ((curByte & 0xC0) != 0x80)
  74. {
  75. return false;
  76. }
  77. charByteCounter--;
  78. }
  79. }
  80. if (charByteCounter > 1)
  81. {
  82. throw new Exception("非预期的byte格式");
  83. }
  84. return true;
  85. }
  86. #endregion
  87. }
  88. }