Windows 1251 is not a supported encoding name for information on defining a custom encoding

I am writing WinPhone 8.1 app.
Code is very simple and works in most cases:

string htmlContent;
using (var client = new HttpClient())
{
    htmlContent = await client.GetStringAsync(GenerateUri());
}
_htmlDocument.LoadHtml(htmlContent);

But sometimes exception is thrown at

htmlContent = await client.GetStringAsync(GenerateUri());

InnerException {System.ArgumentException: ‘windows-1251’ is not a
supported encoding name. Parameter name: name at
System.Globalization.EncodingTable.internalGetCodePageFromName(String
name) at
System.Globalization.EncodingTable.GetCodePageFromName(String name)
at
System.Net.Http.HttpContent.<>c__DisplayClass1.b__0(Task
task)} System.Exception {System.ArgumentException}

Does HttpClient support 1251 encoding? And if it doesn’t, how can I avoid this problem? Or is it target page problem? Or am I wrong in something?

tukaef's user avatar

tukaef

9,0944 gold badges29 silver badges45 bronze badges

asked Jul 26, 2015 at 14:22

Kirill Lappo's user avatar

0

Get response as IBuffer and then convert using .NET encoding classes:

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(uri);
IBuffer buffer = await response.Content.ReadAsBufferAsync();
byte[] bytes = buffer.ToArray();

Encoding encoding = Encoding.GetEncoding("windows-1251");
string responseString = encoding.GetString(bytes, 0, bytes.Length);

answered Jul 26, 2015 at 17:54

kiewic's user avatar

kiewickiewic

15.9k13 gold badges79 silver badges102 bronze badges

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Cito 
{
    class Program
    {
        static void Main(string[] args)
        {
 
           string a = File.ReadAllText("1.txt", Encoding.GetEncoding(1251));
           string b = File.ReadAllText("2.txt", Encoding.GetEncoding(1251));
 
            int nom;
        int smehenie;
        string rezyltat;
        int per,per2 ;
        int nym = 0;
        char[] massage = a.ToCharArray();
        char[] key = b.ToCharArray();
 
            char[] alfavit = { 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я' };
 
            // Перебираем каждый символ сообщения
            for (int i = 0; i < massage.Length; i++)
            {
                // Ищем индекс буквы
                for (per = 0; per < alfavit.Length; per++)
                {
                    if (massage[i] == alfavit[per])
                    {
                        break;
                    }
                }
 
                if (per != 33) // Если j равно 33, значит символ не из алфавита
                {
                    nom = per; // Индекс буквы
 
                    // Ключ закончился - начинаем сначала.
                    if (nym > key.Length - 1) { nym = 0; }
 
                    // Ищем индекс буквы ключа
                    for (per2 = 0; per2 < alfavit.Length; per2++)
                    {
                        if (key[nym] == alfavit[per2])
                        {
                            break;
                        }
                    }
 
                    nym++;
 
                    if (per2 != 33) // Если f равно 33, значит символ не из алфавита
                    {
                        smehenie = nom + per2;
                    }
                    else
                    {
                        smehenie = nom;
                    }
 
                    // Проверяем, чтобы не вышли за пределы алфавита
                    if (smehenie > 32)
                    {
                        smehenie = smehenie - 33;
                    }
 
                    massage[i] = alfavit[smehenie]; // Меняем букву
                }
            }
 
            rezyltat = new string(massage); // Собираем символы обратно в строку.
            File.WriteAllText("3.txt", rezyltat); // Записываем результат в файл.
 
        }
 
    }
}

@zrhyvr

In universal windows app, calling Encoding.GetEncoding(«windows-1251») will throw an exception

An exception of type ‘System.ArgumentException’ occurred in mscorlib.ni.dll but was not handled in user code

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

same for euc-kr charset.

@ellismg

You will likely need to reference the System.Text.Encoding.CodePages package and then use Encoding.RegisterProvider.

This Stack Overflow answer addresses a similar problem. I expect the answer will work for you as well.

The reason this is done was to remove the need to carry encoding data with ever UWP app, even if the apps did not use them.

@zrhyvr

@msftgits
msftgits

transferred this issue from dotnet/corefx

Jan 31, 2020

@msftbot
msftbot
bot

locked as resolved and limited conversation to collaborators

Jan 1, 2021

I am writing WinPhone 8.1 app.
Code is very simple and works in most cases:

string htmlContent;
using (var client = new HttpClient())
{
    htmlContent = await client.GetStringAsync(GenerateUri());
}
_htmlDocument.LoadHtml(htmlContent);

But sometimes exception is thrown at

htmlContent = await client.GetStringAsync(GenerateUri());

InnerException {System.ArgumentException: ‘windows-1251’ is not a
supported encoding name. Parameter name: name at
System.Globalization.EncodingTable.internalGetCodePageFromName(String
name) at
System.Globalization.EncodingTable.GetCodePageFromName(String name)
at
System.Net.Http.HttpContent.<>c__DisplayClass1.b__0(Task
task)} System.Exception {System.ArgumentException}

Does HttpClient support 1251 encoding? And if it doesn’t, how can I avoid this problem? Or is it target page problem? Or am I wrong in something?

tukaef's user avatar

tukaef

9,0944 gold badges29 silver badges45 bronze badges

asked Jul 26, 2015 at 14:22

Kirill Lappo's user avatar

0

Get response as IBuffer and then convert using .NET encoding classes:

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(uri);
IBuffer buffer = await response.Content.ReadAsBufferAsync();
byte[] bytes = buffer.ToArray();

Encoding encoding = Encoding.GetEncoding("windows-1251");
string responseString = encoding.GetString(bytes, 0, bytes.Length);

answered Jul 26, 2015 at 17:54

kiewic's user avatar

kiewickiewic

15.9k13 gold badges79 silver badges102 bronze badges

2

Question:

It is necessary to translate the text in the windows-1251 encoding into a string from the byte array. I use the built-in tool for this:

Encoding encoding = Encoding.GetEncoding("windows-1251");

However, this code throws an exception:

'windows-1251' is not a supported encoding name.
Parameter name: name

I just can’t understand what is wrong here, on the Internet and even on the English-language stackoverflow, this is how the coding issue is solved.

Answer:

Apparently System.Text.Encoding only supports three encodings:

System.Text.Encoding.BigEndianUnicode
System.Text.Encoding.Unicode
System.Text.Encoding.UTF8

Accordingly, it cannot find windows-1251. For he does not know such an encoding.

To use windows-1251 encoding, you need to implement your class inheriting from System.Text.Encoding and describing this encoding.

Like that:

public class Windows1251 : Encoding 
{
    static string alpha = "\0\a\b\t\n\v\f\r !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя";
    public override int GetByteCount(char[] chars, int index, int count)
    {
        return count;
    }

    public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
    {
        byte questionIndex = (byte)alpha.IndexOf('?');
        for (int i = 0; i < charCount; i++)
        {
            int toIndex = byteIndex + i;
            int index = alpha.IndexOf(chars[charIndex + i]);
            if (index == -1)
                bytes[toIndex] = questionIndex;
            else
                bytes[toIndex] = (byte)index;
        }
        return charCount;
    }

    public override int GetCharCount(byte[] bytes, int index, int count)
    {
        return count;
    }

    public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
    {
        for (int i = 0; i < byteCount; i++)
        {
            chars[i + charIndex] = alpha[bytes[byteIndex + i]];
        }
        return byteCount;
    }

    public override int GetMaxByteCount(int charCount)
    {
        return charCount;
    }

    public override int GetMaxCharCount(int byteCount)
    {
        return byteCount;
    } 

}

Post Views: 18

  • Windows 11 язык для каждого приложения
  • Windows 2000 sp4 скачать торрент
  • Windows 2000 sp4 rollup 1
  • Windows 2000 с драйверами sata
  • Windows 2000 professional sp4 rus скачать iso оригинальный образ