C# Unity function to escape URL querystring parameters

I’m looking for a C# or Unity function to escape a URL querystring parameter the same way that the javascript escape function does it.

I’ve tried the WWW.EscapeURL but it seems to produce multiple character encoding for a single character e.g.

WWW.EscapeURL("De Grâve"); // De+Gr%c3%a2ve

I’m looking for :

De%20Gr%E2ve

This seems to correspond to a javascript call using the escape function:

escape('De Grâve') // = De%20Gr%E2ve
encodeURI('De Grâve') // = De%20Gr%C3%A2ve
encodeURIComponent('De Grâve') // = De%20Gr%C3%A2ve

That’s weird - because WWW.UnEscapeURL worked for me converting for instance “%20” to a space.

HttpUtility.UrlEncode should do the trick for you:
http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode(v=vs.80).aspx

It’s available in .NET 2.0, so should work in Unity.

I ended up using the escape method pulled from the Microsoft.JScript.dll

Source: http://weblog.west-wind.com/posts/2007/Jul/14/Embedding-JavaScript-Strings-from-an-ASPNET-Page#658038

[NotRecommended("escape"), JSFunction(JSFunctionAttributeEnum.None, JSBuiltin.Global_escape)]
public static string escape(object @string)
{
    string str = Convert.ToString(@string);
    string str2 = "0123456789ABCDEF";
    int length = str.Length;
    StringBuilder builder = new StringBuilder(length * 2);
    int num3 = -1;
    while (++num3 < length)
    {
        char ch = str[num3];
        int num2 = ch;
        if ((((0x41 > num2) || (num2 > 90)) &&
             ((0x61 > num2) || (num2 > 0x7a))) &&
             ((0x30 > num2) || (num2 > 0x39)))
        {
            switch (ch)
            {
                case '@':
                case '*':
                case '_':
                case '+':
                case '-':
                case '.':
                case '/':
                    goto Label_0125;
            }
            builder.Append('%');
            if (num2 < 0x100)
            {
                builder.Append(str2[num2 / 0x10]);
                ch = str2[num2 % 0x10];
            }
            else
            {
                builder.Append('u');
                builder.Append(str2[(num2 >> 12) % 0x10]);
                builder.Append(str2[(num2 >> 8) % 0x10]);
                builder.Append(str2[(num2 >> 4) % 0x10]);
                ch = str2[num2 % 0x10];
            }
        }
    Label_0125:
        builder.Append(ch);
    }
    return builder.ToString();
}