如何在 .NET 中猜测没有 BOM 的文件的编码?

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

问题描述

我在 .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 的文件的编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)