Why is System.-Encoding and the Default-Encoding different (.NET Core)?

Viewed 2406

I have a C# .NET Core application.
I run

System.Console.WriteLine(System.Text.Encoding.Default.WebName);

and I get utf-8

However, if I open PowerShell, and issue

[System.Text.Encoding]::Default

I get

IsSingleByte      : True
BodyName          : iso-8859-1
EncodingName      : Westeuropäisch (Windows)
HeaderName        : Windows-1252
WebName           : Windows-1252
WindowsCodePage   : 1252
IsBrowserDisplay  : True
IsBrowserSave     : True
IsMailNewsDisplay : True
IsMailNewsSave    : True
EncoderFallback   : System.Text.InternalEncoderBestFitFallback
DecoderFallback   : System.Text.InternalDecoderBestFitFallback
IsReadOnly        : True
CodePage          : 1252

Why is the system-encoding different from the default-encoding ?
And how do I get the system-encoding under these circumstances ?
I mean, I figured out I can get Windows-Codepage 1252 in .NET Core with

System.Text.Encoding.GetEncoding("iso-8859-1").WindowsCodePage

but how do I determine the system's codepage ?

2 Answers

Ah, got it myselfs, what still works is getting the codepage over the current culture (or the InstalledUICulture):

public static System.Text.Encoding GetSystemEncoding()
{
    // The OEM code page for use by legacy console applications
    // int oem = System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage;

    // The ANSI code page for use by legacy GUI applications
    // int ansi = System.Globalization.CultureInfo.InstalledUICulture.TextInfo.ANSICodePage; // Machine 
    int ansi = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage; // User 

    try
    {
        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        System.Text.Encoding enc = System.Text.Encoding.GetEncoding(ansi);
        return enc;
    }
    catch (System.Exception)
    { }


    try
    {

        foreach (System.Text.EncodingInfo ei in System.Text.Encoding.GetEncodings())
        {
            System.Text.Encoding e = ei.GetEncoding();

            // 20'127: US-ASCII 
            if (e.WindowsCodePage == ansi && e.CodePage != 20127)
            {
                return e;
            }

        }
    }
    catch (System.Exception)
    { }

    // return System.Text.Encoding.GetEncoding("iso-8859-1");
    return System.Text.Encoding.UTF8;
}

You can simply use

System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
var enc = System.Text.Encoding.GetEncoding(0);

The value 0 means CP_ACP for the native API. This continues to work on .NET 6.

Related