Why can't I find or use UrlEncode in Visual Studio 2010?

Sootah picture Sootah · Feb 11, 2011 · Viewed 20.3k times · Source

I have a string that I'd like to encode into the standard URL format. From what I've found, I should be able to do this via the httpUtility.urlEncode method, but I don't seem to have that available.

I've added "using" references to both System.Web and System.Net to no avail. I've also seen other references to server.urlEncode amongst other variants, but I don't see the method anywhere.

I'm using the latest version of C# in Visual Studio 2010. Is the method called something different in this version, hidden somewhere else, or am I completely off base?

Answer

Cody Gray picture Cody Gray · Feb 11, 2011

By default, new projects in Visual Studio 2010 target the .NET Framework 4.0 Client Profile, which does not include the System.Web assembly.

You can change the version of the Framework that your project targets in your project's Properties. Under the "Application" tab, select ".NET Framework 4.0" from the combobox labeled "Target framework".

Then, make sure that you have added a reference to System.Web using the "Add Reference" dialog.

Finally, add a using directive to the top of your class for the System.Web namespace:

using System.Web;


You'll find the various overloads of the UrlEncode method in the HttpUtility class. Sample code:

HttpUtility.UrlEncode("http://www.google.com/");