問題描述
我在 .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 的文件的編碼?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!