Home > front end >  Encoding.GetEncodings() is not working properly
Encoding.GetEncodings() is not working properly

Time:06-07

Following code block working well on C# Interactive Compiler

Microsoft (R) Visual C# Interactive Compiler version 4.2.0-4.22252.24 ()
Loading context from 'CSharpInteractive.rsp'.
Type "#help" for more information.
> using System.Text;
> var codepages = Encoding.GetEncodings().Select(x => x.GetEncoding()).ToList();
> foreach (var cp in codepages) { Console.WriteLine($"{cp.HeaderName} {cp.EncodingName} ({cp.CodePage})"); }

output

1. IBM037 IBM EBCDIC (US-Canada) (37)
2. IBM437 OEM United States (437)
3. IBM500 IBM EBCDIC (International) (500)
..
..
..
138. x-iscii-pa ISCII Punjabi (57011)
139. utf-7 Unicode (UTF-7) (65000)
140. utf-8 Unicode (UTF-8) (65001)

But whenever I want to run it in .net 6.0 winform application

        public MainForm()
        {
            InitializeComponent();
            initView();
            cbEncodings.Items.Clear();
            var codepages = Encoding.GetEncodings().Select(x => x.GetEncoding()).ToList();
            foreach (var e in codepages)
            {
                cbEncodings.Items.Add($"{e.EncodingName} ({e.CodePage})");
            }
        }

it's only lists 7 elements

Output

enter image description here

what could be the reason for this?

CodePudding user response:

Add Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); before your code (i.e. before var codepages = Encoding.GetEncodings().Select(x => x.GetEncoding()).ToList();), then you get the full list. Details are in https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.getencodings?view=net-6.0.

  • Related