• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C#教程 > c#检测文本文件编码的方法

c#检测文本文件编码的方法

作者: 字体:[增加 减小] 来源:互联网 时间:2017-05-28

通过本文主要向大家介绍了马桶c的个人空间,c语言,欲情 c max,维生素c,奔驰c200等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

C#如何检测文本文件的编码,本文为大家分享了示例代码,具体内容如下

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
 
namespace KlerksSoft
{
  public static class TextFileEncodingDetector
  {
    /*
* Simple class to handle text file encoding woes (in a primarily English-speaking tech
* world).
*
* - This code is fully managed, no shady calls to MLang (the unmanaged codepage
* detection library originally developed for Internet Explorer).
*
* - This class does NOT try to detect arbitrary codepages/charsets, it really only
* aims to differentiate between some of the most common variants of Unicode
* encoding, and a "default" (western / ascii-based) encoding alternative provided
* by the caller.
*
* - As there is no "Reliable" way to distinguish between UTF-8 (without BOM) and
* Windows-1252 (in .Net, also incorrectly called "ASCII") encodings, we use a
* heuristic - so the more of the file we can sample the better the guess. If you
* are going to read the whole file into memory at some point, then best to pass
* in the whole byte byte array directly. Otherwise, decide how to trade off
* reliability against performance / memory usage.
*
* - The UTF-8 detection heuristic only works for western text, as it relies on
* the presence of UTF-8 encoded accented and other characters found in the upper
* ranges of the Latin-1 and (particularly) Windows-1252 codepages.
*
* - For more general detection routines, see existing projects / resources:
* - MLang - Microsoft library originally for IE6, available in Windows XP and later APIs now (I think?)
* - MLang .Net bindings: http://www.codeproject.com/KB/recipes/DetectEncoding.aspx
* - CharDet - Mozilla browser's detection routines
* - Ported to Java then .Net: http://www.conceptdevelopment.net/Localization/NCharDet/
* - Ported straight to .Net: http://code.google.com/p/chardetsharp/source/browse
*
* Copyright Tao Klerks, Jan 2010, tao@klerks.biz
* Licensed under the modified BSD license:
*
 
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
 
- Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
- The name of the author may not be used to endorse or promote products derived from
this software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
 
*
*/
 
    const long _defaultHeuristicSampleSize = 0x10000; //completely arbitrary - inappropriate for high numbers of files / high speed requirements
 
    public static Encoding DetectTextFileEncoding(string InputFilename, Encoding DefaultEncoding)
    {
      using (FileStream textfileStream = File.OpenRead(InputFilename))
      {
        return DetectTextFileEncoding(textfileStream, DefaultEncoding, _defaultHeuristicSampleSize);
      }
    }
 
    public static Encoding DetectTextFileEncoding(FileStream InputFileStream, Encoding DefaultEncoding, long HeuristicSampleSize)
    {
      if (InputFileStream == null)
        throw new ArgumentNullException("Must provide a valid Filestream!", "InputFileStream");
 
      if (!InputFileStream.CanRead)
        throw new ArgumentException("Provided file stream is not readable!", "InputFileStream");
 
      if (!InputFileStream.CanSeek)
        throw new ArgumentException("Provided file stream cannot seek!", "InputFileStream");
 
      Encoding encodingFound = null;
 
      long originalPos = InputFileStream.Position;
 
      InputFileStream.Position = 0;
 
      //First read only what we need for BOM detection
 
      byte[] bomBytes = new byte[InputFileStream.Length > 4 ? 4 : InputFileStream.Length];
      InputFileStream.Read(bomBytes, 0, bomBytes.Length);
 
      encodingFound = DetectBOMBytes(bomBytes);
 
      if (encodingFound != null)
      {
        InputFileStream.Position = originalPos;
        return encodingFound;
      }
 
      //BOM Detection failed, going for heuristics now.
      // create sample byte array and populate it
      byte[] sampleBytes = new byte[HeuristicSampleSize > InputFileStream.Length ? InputFileStream.Length : HeuristicSampleSize];
      Array.Copy(bomBytes, sampleBytes, bomBytes.Length);
      if (InputFileStream.Length > bomBytes.Length)
        InputFileStream.Read(sampleBytes, bomBytes.Length, sampleBytes.Length - bomBytes.Length);
      InputFileStream.Position = originalPos;
 
      //test byte array content
      encodingFound = DetectUnicodeInByteSampleByHeuristics(sampleBytes);
 
      if (encodingFound != null)
        return encodingFound;
      else
        return DefaultEncoding;
    }
 
    public static Encoding DetectTextByteArrayEncoding(byte[] TextData, Encoding DefaultEncoding)
    {
      if (TextData == null)
        throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");
 
      Encoding encodingFound = null;
 
      encodingFound = DetectBOMBytes(TextData);
 
      if (encodingFound != null)
      {
        return encodingFound;
      }
      else
      {
        //test byte array content
        encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData);
 
        if (encodingFound != null)
          return encodingFound;
        else
          return DefaultEncoding;
      }
 
    }
 
    public static Encoding DetectBOMBytes(byte[] BOMBytes)
    {
      if (BOMBytes == null)
        throw new ArgumentNullException("Must provide a valid BOM byte array!", "BOMBytes");
 
      if (BOMBytes.Length < 2)
        return null;
 
      if (BOMBytes[0] == 0xff
        && BOMBytes[1] == 0xfe
        && (BOMBytes.Length < 4
          || BOMBytes[2] != 0
          || BOMBytes[3] != 0
          )
        )
        return Encoding.Unicode;
 
      if (BOMBytes[0] == 0xfe
        && BOMBytes[1] == 0xff
        )
        return Encoding.BigEndianUnicode;
 
      if (BOMBytes.Length < 3)
        return null;
 
      if (BOMBytes[0] == 0xef && BOMBytes[1] == 0xbb && BOMBytes[2] == 0xbf)
        return Encoding.UTF8;
 
      if (BOMBytes[0] == 0x2b && BOMBytes[1] == 0x2f && BOMBytes[2] == 0x76)
        return Encoding.UTF7;
 
      if (BOMBytes.Length < 4)
        return null;
 
      if (BOMBytes[0] == 0xff && BOMBytes[1] == 0xfe && BOMBytes[2] == 0 && BOMBytes[3] == 0)
        return Encoding.UTF32;
 
      if (BOMBytes[0] == 0 && BOMBytes[1] == 0 && BOMBytes[2] == 0xfe && BOMBytes[3] == 0xff)
        return Encoding.GetEncoding(12001);
 
      return null;
    }
 
    public static Encoding DetectUnicodeInByteSampleByHeuristics(byte[] SampleBytes)
    {
      long oddBinaryNullsInSample = 0;
      long evenBinaryNullsInSample = 0;
      long suspiciousUTF8SequenceCount = 0;
      long suspiciousUTF8BytesTotal = 0;
      long likelyUSASCIIBytesInSample = 0;
 
  



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • C#利用ReportViewer生成报表
  • C#基于正则去掉注释的方法示例
  • C#中new的用法及与override的区别分析
  • C#实现两个richtextbox控件滚动条同步滚动的简单方法
  • C# for循环的经典案例集锦
  • C#操作word的方法示例
  • C#使用WebClient登录网站并抓取登录后的网页信息实现方法
  • C# WinForm制作异形窗体与控件的方法
  • C#实现Excel表数据导入Sql Server数据库中的方法
  • C#使用NPOI上传excel

相关文章

  • 2017-05-28C#实现Xml序列化与反序列化的方法
  • 2017-05-28C#实现用户自定义控件中嵌入自己的图标
  • 2017-05-28C#连接ODBC数据源的方法
  • 2017-05-28WinForm中的登录实现
  • 2017-05-28C#多线程学习之(三)生产者和消费者用法分析
  • 2017-05-28C#实现自定义双击事件
  • 2017-05-28深入多线程之:解析线程的交会(Thread Rendezvous)详解
  • 2017-05-28C#操作读取、写入XML文档的实用方法
  • 2017-05-28C#实现把科学计数法(E)转化为正常数字值
  • 2017-05-28C#加密app.config中连接字符串的方法

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • c# socket编程udp客户端实现代码分享
    • c#使用ManagedWifi查看当前Wifi信号并选择wifi的示例
    • 获取wince mac地址与IP地址解决方案
    • .net2.0+ Winform项目实现弹出容器层
    • 详解C#中的定时器Timer类及其垃圾回收机制
    • C#使用iTextSharp设置PDF所有页面背景图功能实例
    • C#迷你猜数实例分析
    • C# IsDefined的问题
    • C# 静态构造函数使用总结
    • c#事件使用示例详解

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有