rsturim
rsturim

Reputation: 6846

How can I pull a value out of a QueryString-like string with C#

I have an ASP.NET page that has a value stored in the session object.

I want to pull a value out for a specific key -- but remember it's just a string.

Take for example the string below -- what's the best way to get "FOOBAR" from this string? Is regex the best way?

sometimes it could appear this way:

"?facets=All Groups||Brand&TitleTag=FOOBAR#back"

other times it could appear this way:

"?facets=All Groups||Brand&TitleTag=FOOBAR"

UPDATE: SOLUTION

Thanks jglouie for the idea to use 'ParseQueryString' -- that ultimately did the trick. The code sample you provided was a good start. Below is my final solution:

System.Collections.Specialized.NameValueCollection pairs = HttpUtility.ParseQueryString(facetStateOrURL);
string titleTagValue = pairs["TitleTag"];
if (!String.IsNullOrEmpty(titleTagValue) && titleTagValue.IndexOf('#') > -1)
{
    titleTagValue = titleTagValue.Substring(0, titleTagValue.IndexOf('#'));
}

Thanks again for the help!

Upvotes: 0

Views: 159

Answers (2)

jglouie
jglouie

Reputation: 12880

What about HttpUtility's ParseQueryString() method?

http://msdn.microsoft.com/en-us/library/ms150046.aspx

--

Added sample with Jethro's suggestion:

var string1 = "?facets=All Groups||Brand&TitleTag=FOOBAR#back";
var pairs = HttpUtility.ParseQueryString(string1);

string titleTagValue = pairs["TitleTag"];

if (!string.IsNullOrEmpty(titleTagValue) && titleTagValue.IndexOf('#') > -1)
{
    titleTagValue = titleTagValue.Substring(0, titleTagValue.IndexOf('#'));
}

Upvotes: 9

Brady Holt
Brady Holt

Reputation: 2924

It looks like you are grabbing the page request querystring and adding it to the session container at some point. Instead of grabbing the whole querystring and putting it in the seesion couldn't you just grab the part of the querystring you need and save it to a specfic session key?

For instance:

Session["TitleTag"] = Request.QueryString["TitleTag"]

Then you can reference Session["TitleTag"] when you need it. This way you don't have to parse the string and the data contained in the session is more self describing.

Upvotes: 0

Related Questions