예제 #1
0
        // 将来的に Read と差し替える予定
        public static string ReadVer2(string path, EncodingPriority priority)
        {
            byte[] data = File.ReadAllBytes(path);

            Encoding shift_jis          = Encoding.GetEncoding(932, new EncoderExceptionFallback(), new DecoderExceptionFallback());
            Encoding shift_jis_no_error = Encoding.GetEncoding(932);
            Encoding utf8          = new UTF8Encoding(true, true);
            Encoding utf8_no_error = new UTF8Encoding(true, false);

            if (priority == EncodingPriority.Auto)
            {
                byte[] head = new byte[Math.Min(4096, data.Length)]; // 先頭 4096 バイトから推定

                Array.Copy(data, head, head.Length);
                priority = (IsUTF8(head) ? EncodingPriority.UTF8 : EncodingPriority.ShiftJIS);
            }
            string ret_str = "";

            if (priority == EncodingPriority.ShiftJIS) // Shift_JIS 優先
            {
                try
                {
                    // まず Shift_JIS として読み込んでみる
                    ret_str = shift_jis.GetString(data);
                }
                catch (DecoderFallbackException)
                {
                    // 失敗したら UTF-8 として読み込む
                    if (IsUTF8BomPresent(data))
                    {
                        ret_str = utf8_no_error.GetString(data, 3, data.Length - 3);
                    }
                    else
                    {
                        ret_str = utf8_no_error.GetString(data);
                    }
                }
            }
            else
            {
                try
                {
                    // まず UTF-8 として読み込んでみる
                    if (IsUTF8BomPresent(data))
                    {
                        ret_str = utf8.GetString(data, 3, data.Length - 3);
                    }
                    else
                    {
                        ret_str = utf8.GetString(data);
                    }
                }
                catch (DecoderFallbackException)
                {
                    // 失敗したら Shift_JIS として読み込む
                    ret_str = shift_jis_no_error.GetString(data);
                }
            }
            return(ret_str);
        }
예제 #2
0
 // 将来的に Write と差し替える予定
 public static void WriteVer2(string filename, string contents, EncodingPriority priority)
 {
     if (priority == EncodingPriority.ShiftJIS)
     {
         File.WriteAllText(filename, contents, Encoding.GetEncoding(932));
     }
     else
     {
         // UTF8 BOM付きで書き込む
         Encoding utf8 = new UTF8Encoding(true, true);
         File.WriteAllText(filename, contents, utf8);
     }
 }