2020年8月16日 星期日

[C#] 檔案寫入UTF8 或 UTF8 BOM

[C#] 檔案寫入UTF8 或 UTF8 BOM

[C#] 檔案寫入UTF8 或 UTF8 BOM

簡介

一開始使用靜態函式Encoding.UTF8寫入txt檔時,產生檔案為UTF8 with BOM,為了輸出UTF8 without BOM做一下筆記。

UTF8 / UTF8 BOM

  • 產生UTF8 BOM

    Encoding utf8 = new UTF8Encoding(true);
    
  • 產生UTF8

    Encoding utf8 = new UTF8Encoding(false);
    
  • 簡單實作

    class Program
    {
        static void Main(string[] args)
        {
            string utf8file = "utf8file.txt";
    
            if (File.Exists(utf8file))
            {
                File.Delete(utf8file);
            }
    
            using (FileStream fileStream = new FileStream(utf8file, FileMode.Append, FileAccess.Write))
            {
                // Create a UTF-8 encoding.
                using (StreamWriter sw = new StreamWriter(fileStream, new UTF8Encoding(false)))
                {
                    sw.WriteLine("Hello world! (UTF8)");
                }
            }
    
    
            string utf8bomfile = "utf8bomfile.txt";
            if (File.Exists(utf8bomfile))
            {
                File.Delete(utf8bomfile);
            }
    
            using (FileStream fileStream = new FileStream(utf8bomfile, FileMode.Append, FileAccess.Write))
            {
                // Encoding.UTF8 同 new UTF8Encoding(true)
                // Create a UTF-8 encoding that supports a BOM.
                using (StreamWriter sw = new StreamWriter(fileStream, new UTF8Encoding(true)))
                {
                    sw.WriteLine("Hello world! (UTF8 Bom)");
                }
            }
    
        }
    }
    

    產生結果:
    UTF8 With BOM

    UTF8 Without BOM

  • 比較
    UTF8Encoding



參考資料

如有錯誤或建議,歡迎留言指教,謝謝!!

(相關內容如有侵犯隱私或著作權,請協助通知刪除,感謝)

沒有留言:

張貼留言