Posts tagged Universal Apps

In Windows/Windows Phone 8.1 store apps the class HttpUtility is not available to help parse query strings. So instead I decided to write a custom extension method to the Uri class which can parse the query string as a Dictionary<string,string>. My final extension function looks like this:

/// <summary>
/// Parse a query string into a System.Collections.Generic.Dictionary
/// </summary>
/// <param name="uri">Uri to parse query string from</param>
public static Dictionary<string, string> ParseQueryString(this Uri uri)
   WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query);
   return decoder.ToDictionary(x => x.Name, x => x.Value);

With example usage:

var parsedQueryString = new Uri("").ParseQueryString();
string query = parsedQueryString.ContainsKey("query") ? parsedQueryString["query"] : String.Empty; // Query is "windows phone"
string order = parsedQueryString.ContainsKey("order") ? parsedQueryString["order"] : String.Empty; // Order is "desc"