Feb 20

Written by: Bruce Chapman
Wednesday, February 20, 2008 4:44 PM 

Sometimes you need to parse a query string that is in a string variable, and don't have access to the Request.QueryString object.  In that case, you really want to be able to quickly identify the key/value pairs.

While there are many different ways, here's my take (which is searching for specified terms in the query string, but you could easily modify it to look up by the key value)

 

using System.Text.RegularExpressions;
//split querystring into key/val matches
//takes url as string

MatchCollection qsItems = Regex.Matches(url, @"(?:\&|\?)(?:(?.[^\=\&]*)\=(?.[^\=\&]*))");
foreach (Match itemMatch in qsItems)
{
string val = itemMatch.Groups["val"].Value;
string key = itemMatch.Groups["key"].Value;
switch (key.ToLower())
{
case "tabid":
Int32.TryParse(val, out tabId);
break;
case "portalid":
Int32.TryParse(val, out portalId);
break;
}
}

To lookup on key value, you'd need to use the Regex object and then lookat the GroupNumberByName() function, passing in the name of the group (ie TabId) you are after, then using the resultant number to retrieve the correct Group from the Match.Groups collection.

Most people probably split the Url into an array on the '&' character, but in this case you can just stick the whole Url in and not worry about parsing out all the http://, host, pagename and everything else.

Tags:

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Add Comment   Cancel 
Bruce Chapman
Hi, I'm Bruce Chapman, and this is my blog. You'll find lots of information here - my thoughts about business and the internet, technical information, things I'm working on and the odd strange post or two.

Programmer T-Shirts

T-shirts for programmers
programmer t-shirts
All proceeds to charity