Easiest way to parse "querystring" formatted data

Tom Gullen picture Tom Gullen · Aug 14, 2012 · Viewed 44.2k times · Source

With the following code:

string q = "userID=16555&gameID=60&score=4542.122&time=343114";

What would be the easiest way to parse the values, preferably without writing my own parser? I'm looking for something with the same functionality as Request.querystring["gameID"].

Answer

Chris Shain picture Chris Shain · Aug 14, 2012

Pretty easy... Use the HttpUtility.ParseQueryString method.

Untested, but this should work:

var qs = "userID=16555&gameID=60&score=4542.122&time=343114";
var parsed = HttpUtility.ParseQueryString(qs);
var userId = parsed["userID"]; 
//  ^^^^^^ Should be "16555".  Note this will be a string of course.