NET6 Error System.NotSupportedException: No data is available for encoding 874 …

หลังจากทดสอบ E2E Test เจอว่า Service ที่ Export Text File จะพบ Error เต็มๆว่า

System.NotSupportedException: No data is available for encoding 874. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.

สาเหตุ

  • มาจาก Code ชุดนี้ครับ
File.WriteAllText(outputPath, csv.ToString(), Encoding.GetEncoding(874));
  • Export Text File โดยกำหนด Encoding Windows-874 โดยทางแก้มี 2 แบบครับ
    - ใช้ UTF-8
    - หาทาง Export Encoding Windows-874 เหมือนเดิมครับ
  • สำหรับผมของผมไม่มีทางเลือกครับ เนื่องจากระบบ SAP ปลายทางต้องการ Encoding Windows-874

NET6 (Encoding Windows-874)

  • เนื่องจากใน .NET Core มีการตัดการ Support พวก Encoding ที่ไม่จำเป็นออกไปครับ ถ้าต้องการใช้ Encoding เก่าๆ Windows-874 ดังนั้น ต้องเพิ่ม nuget package System.Text.Encoding.CodePages หรือจะเพิ่มผ่าน command
dotnet add package System.Text.Encoding.CodePages
  • จากนั้นที่ Method Main หลักของ WebAPI หรือ exe นั้นๆ เช่น ตัว program.cs ให้เพิ่มการ Register
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  • สุดท้ายลองทดสอบ Export TextFile แล้วส่งไปยังระบบ SAP ครับ ไม่มี Exception / ระบบ SAP รับข้อมูลได้

Reference


Discover more from naiwaen@DebuggingSoft

Subscribe to get the latest posts to your email.