Search code examples
c#encoding

C# method Encoding.GetEncoding won't find the windows-1252 encoding


i'm trying to get the windows-1252 encoding into a local variable like this:

Encoding win1252 = Encoding.GetEncoding(1252);

which results in an error saying that it can't find the codepage 1252. I've also tried looking for the Encoding via the name (both with a small w and a big one)

Encoding win1252 = Encoding.GetEncoding("windows-1252");

but that also doesnt work. I've tried looking for all Encodings my System can find with the following loop:

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

And it could only find 7 in total. Do i have to install additional Encodings in any way? I'm kind of getting lost with this.


Solution

  • You need to register encodings provider first to use additional encodings like Windows-1252.

    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
    

    CodePagesEncodingProvider provides access to an encoding provider for code pages that otherwise are available only in the desktop .NET Framework.

    So you can find more encodings after that and can get Windows-1252 too:

    Encoding win1252 = Encoding.GetEncoding(1252);
    

    The .NET Framework for the Windows desktop supports a large set of Unicode and code page encodings. .NET Core, on the other hand, supports only the following encodings:

    • ASCII (code page 20127), which is returned by the Encoding.ASCII property.
    • ISO-8859-1 (code page 28591).
    • UTF-7 (code page 65000), which is returned by the Encoding.UTF7 property.
    • UTF-8 (code page 65001), which is returned by the Encoding.UTF8 property.
    • UTF-16 and UTF-16LE (code page 1200), which is returned by the Encoding.Unicode property.
    • UTF-16BE (code page 1201), which is instantiated by calling the UnicodeEncoding.UnicodeEncoding or UnicodeEncoding.UnicodeEncoding constructor with a bigEndian value of true.
    • UTF-32 and UTF-32LE (code page 12000), which is returned by the Encoding.UTF32 property.
    • UTF-32BE (code page 12001), which is instantiated by calling an UTF32Encoding constructor that has a bigEndian parameter and providing a value of true in the method call.

    Other than code page 20127, code page encodings are not supported. The CodePagesEncodingProvider class extends EncodingProvider to make these code pages available to .NET Core.

    Note that you need a reference to System.Text.Encoding.CodePages.dll to use CodePagesEncodingProvider in some .net versions you have to add nuget package to your project.