DotNetCore 提示 系统不支持“big5”编码。System does not support 'big5' encoding.

发布时间 2023-04-14 17:50:41作者: LuoCore

C# .NET Core 以 Big 5 (大五碼)編碼格式讀取檔案 (ruyut.com)

 

 

C# .NET Core 以 Big 5 (大五碼)編碼格式讀取檔案

之前在寫 C# .NET Framework 的時候要使用其他編碼格式很簡單,寫上編碼格式就可以了,但今天在 .NET Core 6.0 讀取檔案使用 Big5(950) 的時候,拋出這個錯誤:
Unhandled exception. System.NotSupportedException: No data is available for encoding 950. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Bash

原來 .NET Core 只有保留最基礎的編碼格式,其他的編碼格式使用的時候需要自己增加

解決方法

只要安裝一個套件和加入一行程式碼就解決了

需要先從 NuGet 安裝 System.Text.Encoding.CodePages
Install-Package System.Text.Encoding.CodePages -Version 6.0.0
Package-manager

註冊使其支援不同的編碼格式
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
C#
接下來就和以前一樣了

程式碼示範: 讀取文件並輸出
using (System.IO.StreamReader reader = new System.IO.StreamReader(@"file.txt", System.Text.Encoding.GetEncoding(950)))
{
    while (!reader.EndOfStream)
    {
        Console.WriteLine(reader.ReadLine());
    }
}