.NET(C#):從檔案中覺察編碼

來源:互聯網
上載者:User

今天遇到一個問題,需要從根據一個檔案嘗試擷取其文本編碼。不是很難呵呵,無非就是根據前幾個位元組判斷字元順序標記(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);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.