ここで紹介するコードはChatGPTで提案されたコードの一つです。
実際に私のアプリで利用しています。
Mozilla Universal Charset DetectorのUde.NetStandardと言うパッケージをNuGetからインストールして使います。
CharsetDetectorクラスが利用するクラスです。
ファイルのパスを渡すと、ファイルのエンコードが推測されて返ってきます。
使い方はいたって簡単です。
using System.IO;
using System.Text;
using Ude;
namespace SampleNS
{
internal class DetectEncoding
{
static public Encoding DetectFileEncoding(string filePath)
{
byte[] buffer = File.ReadAllBytes(filePath);
// BOM チェック
if (buffer.Length >= 2)
{
if (buffer[0] == 0xFF && buffer[1] == 0xFE) return Encoding.Unicode; // UTF-16 LE
if (buffer[0] == 0xFE && buffer[1] == 0xFF) return Encoding.BigEndianUnicode; // UTF-16 BE
if (buffer.Length >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) return Encoding.UTF8; // UTF-8 BOM
}
// BOMがない場合、Udeライブラリでエンコーディング推測
CharsetDetector detector = new CharsetDetector();
detector.Feed(buffer, 0, buffer.Length);
detector.DataEnd();
if (detector.Charset != null)
{
return Encoding.GetEncoding(detector.Charset);
}
// 判別できなかった場合はデフォルト(Shift_JISを仮定)
return Encoding.GetEncoding("Shift_JIS");
}
}
}
