如何猜测.NET中没有BOM的文件的编码? [英] How to guess the encoding of a file with no BOM in .NET?

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

问题描述

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

当文件有BOM时,这可以正常工作,我遇到麻烦的文件没有BOM ..基本上我有乱码当我指定Encoding.Unicode它工作正常,例如:

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

所以,我需要得到文件内容变成一个字符串,那么人们通常如何处理这个问题呢?我知道没有解决方案可以在100%的时间内工作,但是我想提高我的赔率..显然有那些试图猜测的软件例如,记事本,浏览器等)在.NET框架中有一个可以为我猜测的方法吗?有人有ome代码他们想分享?



更多背景:这个问题与我的几乎相同,但是我在.NET领域。这个问题让我有一个博客列出了各种编码检测库,但没有一个是在.NET

解决方案

Libary
http://www.codeproject.com/KB/recipes/DetectEncoding.aspx



也许在stackoverflow上有用的线程


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

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

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();
}

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?

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 http://www.codeproject.com/KB/recipes/DetectEncoding.aspx

And perhaps a useful thread on stackoverflow

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆