Search code examples
c#text.net-corecodepages

How to find OS code page number in .NET Core?


I'm need to get Windows default code page in a .NET Core app. I.e. 1252 on English systems, 1251 on Cyrillic systems, 1253 on Greek, etc. Previously in .NET Framework 4 and Mono it was easily do via Encoding.Default. After the program moved to .NET Core 3.1, now it's need to set code page number manually on each PC by hand. This is not easy for some users.

How to return auto detection of legacy (system) code page? There is no way to read Windows Registry to detect system settings, because the app should also run on Linux with external data received from Windows PCs (or send to that).

Other software which using ANSI code pages for data input and output cannot be rewritten.

Probably OEM code page is interesting too (for seamless interaction with console software, which still using even DOS code page).


Solution

  • The first is a .NET Framework code, the second is its .NET Core equivalent:

    //OutputEncoding = Encoding.Default;
    OutputEncoding = CodePagesEncodingProvider.Instance.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage);
    

    Long, but working correctly on both Windows and Linux.

    DOS, EBCDIC and MacOS encodings can be get similarly via CurrentCulture.TextInfo.*CodePage.