六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 1012|回复: 1

C#自动识别文件编码类

[复制链接]
 楼主| 发表于 2013-4-26 18:12:50 | 显示全部楼层 |阅读模式
//编码问题目前为止,基本上没人解决,就连windows的IE的自动识别有时还识别错编码呢。--yongfa365  
    //如果文件有BOM则判断,如果没有就用系统默认编码,缺点:没有BOM的非系统编码文件会显示乱码。  
    //调用方法: EncodingType.GetType(filename)  
此工具可以结合“写入文件加上bom头,主要适用于utf8文件”使用
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;

  6. namespace GoBuyBatchPublish.publishutils
  7. {
  8.     public class EncodingType
  9.     //编码问题目前为止,基本上没人解决,就连windows的IE的自动识别有时还识别错编码呢。--yongfa365  
  10.     //如果文件有BOM则判断,如果没有就用系统默认编码,缺点:没有BOM的非系统编码文件会显示乱码。  
  11.     //调用方法: EncodingType.GetType(filename)  
  12.     //来源:http://blog.csdn.net/listlofusage/archive/2007/02/10/1506900.aspx  
  13.     {
  14.         public static System.Text.Encoding GetType(string FILE_NAME)
  15.         {
  16.             FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
  17.             System.Text.Encoding r = GetType(fs);
  18.             fs.Close();
  19.             return r;
  20.         }
  21.         public static System.Text.Encoding GetType(FileStream fs)
  22.         {
  23.             /*byte[] Unicode=new byte[]{0xFF,0xFE};
  24.             byte[] UnicodeBIG=new byte[]{0xFE,0xFF};
  25.             byte[] UTF8=new byte[]{0xEF,0xBB,0xBF};*/

  26.             BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
  27.             byte[] ss = r.ReadBytes(3);
  28.             r.Close();
  29.             //编码类型 Coding=编码类型.ASCII;  
  30.             if (ss[0] >= 0xEF)
  31.             {
  32.                 if (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF)
  33.                 {
  34.                     return System.Text.Encoding.UTF8;
  35.                 }
  36.                 else if (ss[0] == 0xFE && ss[1] == 0xFF)
  37.                 {
  38.                     return System.Text.Encoding.BigEndianUnicode;
  39.                 }
  40.                 else if (ss[0] == 0xFF && ss[1] == 0xFE)
  41.                 {
  42.                     return System.Text.Encoding.Unicode;
  43.                 }
  44.                 else
  45.                 {
  46.                     return System.Text.Encoding.Default;
  47.                 }
  48.             }
  49.             else
  50.             {
  51.                 return System.Text.Encoding.Default;
  52.             }
  53.         }



  54.     }
  55. }
复制代码
该会员没有填写今日想说内容.

升级  84.67%

0

主题

0

主题

0

主题

举人

Rank: 3Rank: 3

积分
454
发表于 2014-11-20 11:56:05 | 显示全部楼层
好帖还是要收藏,请继续












30V4A澳规美规开关电源
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表