C#: URLEncode and URLDecode?

Often one needs to make a call to a webserver in .NET, and just as often there is Querystring data that needs to be sent along with this request. Thanksfully .NET has a great WebClient class in System.net.WebClient.  But you can’t just add the querystring data into your URL like such:

Wrong:
WebClient.DownloadFile("http://www.daveamenta.com/file.aspx?mydata=this is a string that I need to send to the server?");

The data needs to be encoded so that the server will not misinterpret the data. This is an example of using an encoded string:

Right:
WebClient.DownloadFile("http://www.daveamenta.com/file.aspx?mydata=this+is+a+string+that+I+need+to+send+to+the+server%3F");

The second string is encoded properly, this way the webserver will properly parse that last ?. This was done using the URLEncode function, .NET has built-in classes for this–but they are a bit hidden. They’re kept in the System.Web namespace. This means that if you are working with .NET on the desktop side, as opposed to ASP.NET, you’ll need to Add a Reference to System.Web.dll. Once you do, you’ll see new classes in System.Web that you can use for many things.

Using URLEncode in C#:

WebClient.DownloadFile( "http://www.daveamenta.com/file.aspx?mydata=" +
System.Web.HttpUtility.UrlEncode( "this is a string that I need to send to the server?" ) );

It is unlikely you will have much use for URLDecode in a C# application, but it is applied the same way.

What exactly is URLEncode?

URLEncode returns a string in which all non-alphanumeric characters other than – (hyphen) _ (underscore), and . (period) have been replaced with a percent (%) sign followed by two hex digits that correspond to the charactor code and spaces encoded as plus (+) signs. Spaces can alternatively be encoded as %20.  20 is (16*2)+(1*0)=32 in decimal, which is the ASCII code for space.

URLDecode will reverse this operation.

May 7, 2008