如何猜测文件的编码

如何猜测文件的编码

本文介绍了如何猜测文件的编码,在.NET中没有BOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用StreamReader类在.NET这样的:

I'm using the StreamReader class in .NET like this:

using( StreamReader reader = new StreamReader( "c:\somefile.html", true ) {
    string filetext = reader.ReadToEnd();
}

这正常工作时,该文件有一个BOM。我遇到了麻烦与没有BOM的文件......基本上我胡言乱语。当我指定Encoding.Uni code它工作得很好,例如:

This works fine when the file has a BOM. I ran into trouble with a file with no BOM .. basically I got gibberish. When I specified Encoding.Unicode it worked fine, eg:

using( StreamReader reader = new StreamReader( "c:\somefile.html", Encoding.Unicode, false ) {
    string filetext = reader.ReadToEnd();
}

所以,我需要获得文件内容转换为字符串。那么,如何才能的人通常处理呢?我知道有没有解决办法,将工作时间的100%,但我想提高我的胜算..有明显的软件在那里,试图猜测(如记事本,浏览器等)。有没有在.NET框架,猜对我的方法?任何人都不会有一些code,他们想与大家分享?

So, I need to get the file contents into a string. So how do people usually handle this? I know there's no solution that will work 100% of the time, but I'd like to improve my odds .. there is obviously software out there that tries to guess (eg, notepad, browsers, etc). Is there a method in the .NET framework that will guess for me? Does anyone have some code they'd like to share?

更多背景:该question为pretty的多少和我一样,但我在.NET土地。这个问题使我的博客,列出各种编码检测库,但没有一个是在.NET

More background: This question is pretty much the same as mine, but I'm in .NET land. That question led me to a blog listing various encoding detection libraries, but none are in .NET

推荐答案

Libary <一href="http://www.$c$cproject.com/KB/recipes/DetectEncoding.aspx">http://www.$c$cproject.com/KB/recipes/DetectEncoding.aspx

和对计算器

And perhaps a useful thread on stackoverflow

这篇关于如何猜测文件的编码,在.NET中没有BOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!