Search code examples
c#windows-store-appsurl-encoding

.NET for Windows Store Apps: UrlEncode


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


Solution

  • 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