问题描述
我在 .NET 中使用 StreamReader 类,如下所示:
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.Unicode 时它工作正常,例如:
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 框架中是否有一种方法可以为我猜测?有没有人有一些他们想分享的代码?
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?
更多背景:这个 问题 与我的几乎相同,但我在 .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
推荐答案
图书馆http://www.codeproject.com/KB/recipes/DetectEncoding.aspx
也许是一个关于 stackoverflow 的有用线程
这篇关于如何在 .NET 中猜测没有 BOM 的文件的编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!