wolfgang ziegler


„make stuff and blog about it“

How to Escape URLs in .NET and C#

January 8, 2015

This one’s a classic: You want to create a URL with a query string programmatically and therefore need some URL encoding functionality.

So, which one of .NET’s UrlEncode methods should you use?

Unfortunately, there are (too) many ways in .NET to perform this seemingly trivial task.

So, here’s what has worked best for me so far:

As long as you can rely on .NET 4.5, use WebUtility.UrlEncode.

If you have to support older versions (back to .NET 2.0) use Uri.EscapeUriString.

Both methods offer a couple of advantages:

  • They live in System.dll and therefore won’t “bloat” your set of required assemblies.
  • They can be used in Portable Class Libraries (you always want to go that way).


Now that I have blogged about that, I know where I can go and look the next time I need this functionality.