如何在 .NET 中猜测没有 BOM 的文件的编码?
- 作者: 用户111002940
- 来源: 51数据库
- 2023-02-13
问题描述
我在 .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 的有用线程
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源