.netcore 讀取ansi編碼

public class FileHelper
    {
        //根據文件自動覺察編碼並輸出內容
       public static string GetText(string path)
        {
            StringBuilder result = new StringBuilder();
            var enc = GetEncoding(path, Encoding.GetEncoding("gb2312"));
            using (var sr = new StreamReader(path, enc))
            {
                result.Append(sr.ReadToEnd());
            }
            return result.ToString();
        }

        /// <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;
        }
    }

調用數組

//首先註冊編碼提供程序
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
//調用
var str=FileHelper.GetText(path);
相關文章
相關標籤/搜索