Windows -1252 is not supported encoding name. C#

2019-04-07 06:08发布

问题:

I am working with windows 10 universal App and the ARM CPU to create apps for the Raspberry Pi. I get the following error with encoding:

Additional information: 'windows-1252' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.

This is my code.

 private async void Login(string passcode)
    {
        try
        {
            MySqlConnection conn = new MySqlConnection("Server=127.0.0.1;Port=3306;Database=database;Uid=username;Pwd=password;SslMode=None;charset=utf8");
            MySqlCommand cmd;

            conn.Open();

            cmd = new MySqlCommand("Select * from users where User = '" + passcode + "'", conn);

            MySqlDataReader dr;

            dr = cmd.ExecuteReader();

            int count = 0;

            while (dr.Read())
            {
                count += 1;
            }

            if(count == 1)
            {
                var dialog = new MessageDialog("Logged In");
                await dialog.ShowAsync();
            }
            else
            {
                var dialog = new MessageDialog("Error");
                await dialog.ShowAsync();
            }

        }
        catch (Exception ex)
        {
            if (ex is MySqlException)
            {
                MySqlException exl = (MySqlException)ex;
                var dialog = new MessageDialog(ex.Message + Environment.NewLine + exl.Number);
                await dialog.ShowAsync();
            }
            else
            {
                var dialog = new MessageDialog(ex.Message + Environment.NewLine);
                await dialog.ShowAsync();
            }

            //throw;
        }
        finally
        {
            conn.Close();
        }


    }
}

I get the error in this line of code

dr = cmd.ExecuteReader();

Before I used to get it in

conn.open();

But I was able to solve it by adding

charset=utf8

to the connection string.

How can I solve this error?

回答1:

I resolved this issue adding

System.Text.EncodingProvider ppp;
ppp = System.Text.CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);


回答2:

From a .NET Core 2.2 I had to Install via Nuget the following two packages:

(System.Text.Encoding & System.Text.Encoding.CodePages)

Then you have to set it before use of libraries:

 using System.Text;
 …
 {
    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
    ...
 }