97
votes

This program works just fine when compiled for .NET 4 but does not when compiled for .NET Core. I understand the error about encoding not supported but not how to fix it.

Public Class Program
    Public Shared Function Main(ByVal args As String()) As Integer
        System.Text.Encoding.GetEncoding(1252)
    End Function
End Class
2
C# is an artifact of MCV here; the tag does not belong.Joshua
c# is language used in answers and question. I does belong here. Also syntax highlighting is broken without it and it's most used language of .NET platform.Vadim Ovchinnikov
@VadimOvchinnikov: I think I'd rather rewrite the code to be in VB .NET which is what it was really in. I didn't at the time because I didn't want to deal with people just claiming VB .NET was not supported when in fact the compiler worked just fine. I'd just have to upload a project file ten times longer than the code.Joshua
This is not a real fix because it changes the code in the question. But if the reason to use codepage 1252 is reading/writing characters of ISO-8859-1 then one could replace it by 28591 which is included in .NET Core without adding a CodePages package: docs.microsoft.com/en-us/dotnet/api/… Be aware that some characters beyond ISO-8859-1are different in codepage 1252 en.wikipedia.org/wiki/ISO/IEC_8859-1#Windows-1252, especially the Euro sign (€).stb

2 Answers

192
votes

To do this, you need to register the CodePagesEncodingProvider instance from the System.Text.Encoding.CodePages package.

To do that, install the System.Text.Encoding.CodePages package:

dotnet add package System.Text.Encoding.CodePages

Then (after implicitly or explicitly running dotnet restore) you can call:

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var enc1252 = Encoding.GetEncoding(1252);

Alternatively, if you only need that one code page, you can get it directly, without registration:

var enc1252 = CodePagesEncodingProvider.Instance.GetEncoding(1252);
12
votes

Please write:

<ItemGroup>
    <PackageReference Include="System.Text.Encoding.CodePages" Version="4.3.0" />
</ItemGroup>

in csproj.

In package console write ' dotnet restore', restore assemblies.

and wite this code for sample:

public class MyClass
{
    static MyClass()
    {
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
    }
}