Tuesday, 19 April 2011

Upper Case URL Encoding in C#

Recently, I was faced with the following problem: I was cloning a HTTP call in C# and had to encode a URL in Upper case as the server was not accepting the URL encoded in lower case.
So basically, what I wanted was:


instead of


I poked around a little and found that by default C# encodes URLs in lowercase. This is what you might call a limitation in C#. So I did the following work around:

I encoded the URL normally through System.Web.HttpUtility.UrlEncode()

And then wrote this simple function which finds the % in the encoded URL and simply converts the next 2 characters to uppercase:

char[] lcencode = System.Web.HttpUtility.UrlEncode(URL).ToCharArray();

for (int i = 0; i < lcencode.Length - 2; i++)
if (lcencode[i] == '%')
lcencode[i + 1] = char.ToUpper(lcencode[i + 1]);
lcencode[i + 2] = char.ToUpper(lcencode[i + 2]);

string ucencode = new string(lcencode);

Now, ucencode will have the URL encoded with Upper Case.

1 comment:

Anonymous said...

Thanks. I have the same issue and thought of manually converting them too. I hoped there would be another way, but looks like that's not the case. Cheers