Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Created April 24, 2023 18:30
Show Gist options
  • Save ArtemAvramenko/51986f87edac697a106fe7fa41b052a7 to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/51986f87edac697a106fe7fa41b052a7 to your computer and use it in GitHub Desktop.
Get ANSI Encoding by LCID in .NET Framework
using System.Runtime.InteropServices;
using System.Text;
namespace App.Encoding
{
class Program
{
[DllImport("kernel32.dll")]
static extern int GetSystemDefaultLCID();
private static readonly Dictionary<int, int> _lcidToCodePage = new()
{
{1025, 1256}, {1026, 1251}, {1028, 950}, {1029, 1250}, {1032, 1253}, {1037, 1255},
{1038, 1250}, {1041, 932}, {1042, 949}, {1045, 1250}, {1048, 1250}, {1049, 1251},
{1050, 1250}, {1051, 1250}, {1052, 1250}, {1054, 874}, {1055, 1254}, {1056, 1256},
{1058, 1251}, {1059, 1251}, {1060, 1250}, {1061, 1257}, {1062, 1257}, {1063, 1257},
{1065, 1256}, {1066, 1258}, {1068, 1250}, {1071, 1251}, {1080, 1256}, {1087, 1251},
{1088, 1251}, {1091, 1250}, {1092, 1251}, {1104, 1251}, {2049, 1256}, {2052, 936},
{2074, 1250}, {2080, 1256}, {2087, 1257}, {2092, 1251}, {2115, 1251}, {3073, 1256},
{3076, 950}, {3098, 1251}, {4097, 1256}, {4100, 936}, {5121, 1256}, {5124, 950},
{6145, 1256}, {6153, 1256}, {7169, 1256}, {8193, 1256}, {9217, 1256}, {9225, 1256},
{10241, 1256}, {11265, 1256}, {12289, 1256}, {13313, 1256}, {14337, 1256},
{15361, 1256}, {16385, 1256}
};
static Encoding GetAnsiEncodingByLCID(int lcid)
{
if (!_lcidToCodePage.TryGetValue(lcid, out var codepage))
{
codepage = 1252;
}
return Encoding.GetEncoding(codepage);
}
static void Main()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var lcid = GetSystemDefaultLCID();
var encoding = GetAnsiEncodingByLCID(lcid);
var s = $"{encoding.EncodingName}, {encoding.WebName}, {encoding.HeaderName}, {encoding.BodyName}";
Console.WriteLine(s);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment