C#判断文件编码的类 虽然有很大缺陷,但目前只能这样了

2009年4月14日星期二

C#判断文件编码的类 虽然有很大缺陷,但目前只能这样了


  1. public class EncodingType

  2. //编码问题目前为止,基本上没人解决,就连windows的IE的自动识别有时还识别错编码呢。--yongfa365

  3. //如果文件有BOM则判断,如果没有就用系统默认编码,缺点:没有BOM的非系统编码文件会显示乱码。

  4. //调用方法: EncodingType.GetType(filename)

  5. //来源:http://blog.csdn.net/listlofusage/archive/2007/02/10/1506900.aspx

  6. {

  7. public static System.Text.Encoding GetType(string FILE_NAME)

  8. {

  9. FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);

  10. System.Text.Encoding r = GetType(fs);

  11. fs.Close();

  12. return r;

  13. }

  14. public static System.Text.Encoding GetType(FileStream fs)

  15. {

  16. /*byte[] Unicode=new byte[]{0xFF,0xFE};

  17. byte[] UnicodeBIG=new byte[]{0xFE,0xFF};

  18. byte[] UTF8=new byte[]{0xEF,0xBB,0xBF};*/


  19. BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);

  20. byte[] ss = r.ReadBytes(3);

  21. r.Close();

  22. //编码类型 Coding=编码类型.ASCII;

  23. if (ss[0] >= 0xEF)

  24. {

  25. if (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF)

  26. {

  27. return System.Text.Encoding.UTF8;

  28. }

  29. else if (ss[0] == 0xFE && ss[1] == 0xFF)

  30. {

  31. return System.Text.Encoding.BigEndianUnicode;

  32. }

  33. else if (ss[0] == 0xFF && ss[1] == 0xFE)

  34. {

  35. return System.Text.Encoding.Unicode;

  36. }

  37. else

  38. {

  39. return System.Text.Encoding.Default;

  40. }

  41. }

  42. else

  43. {

  44. return System.Text.Encoding.Default;

  45. }

  46. }

  47. }


0 评论:

发表评论