今天遇到一個問題,需要從根據一個檔案嘗試擷取其文本編碼。不是很難呵呵,無非就是根據前幾個位元組判斷字元順序標記(BOM),如果檔案不包含BOM的話,返回一個預設值。
代碼:
/// <summary>
/// 根據檔案嘗試返回字元編碼
/// </summary>
/// <param name="file">檔案路徑</param>
/// <param name="defEnc">沒有BOM返回的預設編碼</param>
/// <returns>如果檔案無法讀取,返回null。否則,返回根據BOM判斷的編碼或者預設編碼(沒有BOM)。</returns>
static Encoding GetEncoding(string file, Encoding defEnc)
{
using (var stream = File.OpenRead(file))
{
//判斷流可讀?
if (!stream.CanRead)
return null;
//位元組數組儲存BOM
var bom = new byte[4];
//實際讀入的長度
int readc;
readc = stream.Read(bom, 0, 4);
if (readc >= 2)
{
if (readc >= 4)
{
//UTF32,Big-Endian
if (CheckBytes(bom, 4, 0x00, 0x00, 0xFE, 0xFF))
return new UTF32Encoding(true, true);
//UTF32,Little-Endian
if (CheckBytes(bom, 4, 0xFF, 0xFE, 0x00, 0x00))
return new UTF32Encoding(false, true);
}
//UTF8
if (readc >= 3 && CheckBytes(bom, 3, 0xEF, 0xBB, 0xBF))
return new UTF8Encoding(true);
//UTF16,Big-Endian
if (CheckBytes(bom, 2, 0xFE, 0xFF))
return new UnicodeEncoding(true, true);
//UTF16,Little-Endian
if (CheckBytes(bom, 2, 0xFF, 0xFE))
return new UnicodeEncoding(false, true);
}
return defEnc;
}
}
//輔助函數,判斷位元組中的值
static bool CheckBytes(byte[] bytes, int count, params int[] values)
{
for (int i = 0; i < count; i++)
if (bytes[i] != values[i])
return false;
return true;
}
比如,使用上面的代碼,檢查“我的文件”目錄中所有TXT檔案的編碼資訊:
foreach (var file in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "*.txt"))
Console.WriteLine("{0}\n{1}\n", file, GetEncoding(file, Encoding.ASCII).EncodingName);