Parsing query string without regex in C#

Sometimes you want to get a key/value pair out of a URL, such as:
http://www.maffelu.net?id=19&token=SomethingElse

If we’d like to extract the ‘id’ value the first that comes to mind is “use a regex!”. Well, we don’t have to since the .NET framework has already solved this for us with the HttpUtility class in the System.Web namespace.
Here’s a simple example of how to use it:

class Program
{
	public static void Main(string[] args)
	{
		string url = "http://www.maffelu.net?id=19&token=SomethingElse";
		Dictionary<string, string> queryValues = GetQueryValues(url);
 
		Console.WriteLine("Id value is {0}", queryValues["id"]);
		Console.WriteLine("Token value is {0}", queryValues["token"]);
 
		Console.Read();
	}
 
	private static Dictionary<string, string> GetQueryValues(string url)
	{
		//Create a Uri from the Url
		Uri uri = new Uri(url);
 
		//Parse the Query part of the url
		NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(uri.Query);
 
		//Generate a dictionary with the keys and values
		Dictionary<string, string> queryValues = new Dictionary<string, string>();
		foreach(string key in nameValueCollection.Keys)
		{
			queryValues.Add(key, nameValueCollection[key]);
		}
 
		return queryValues;
	}
}

this will output:
Id value is 19
Token value is SomethingElse