Domanda

In some Windows Store App I need send URL like

new Uri(string.Format(@"http://www.site.com?word={0}",
                                      sourceText))

, where sourceText is the escaped representation of some text. It would be easy, if I need UTF-8, but I need Windows-1251 encoding.

I have tried

    byte[] unicodeBytes = Encoding.Unicode.GetBytes(sourceText);
    byte[] win1251bytes = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding("windows-1251"), unicodeBytes);
    string sourceText =
        Uri.EscapeUriString(Encoding.GetEncoding("windows-1251").GetString(win1251bytes, 0, win1251bytes.Length));

but Uri.EscapeUriString use string, which converting to Unicode automatically.

I could use HttpUtility.UrlEncode(word, Encoding.GetEncoding(1251), but there is no System.Web.HttpUtility in .NET for Windows Store.

For example, 'привет' in UTF-8: %D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82; in Windows-1251 : %EF%F0%E8%E2%E5%F2. I need second string

È stato utile?

Soluzione 2

string sourceText = "привет";
byte[] win1251bytes = Encoding.GetEncoding("windows-1251").GetBytes(sourceText);
string hex = BitConverter.ToString(win1251bytes);
string result = "%" + hex.Replace("-", "%");
// Result: %EF%F0%E8%E2%E5%F2

Altri suggerimenti

How about WebUtility.UrlEncode?

It lives in the System.Net namespace, more info here: http://msdn.microsoft.com/en-us/library/system.net.webutility.urlencode.aspx

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top