26

I have a querystring alike value set in a plain string. I started to split string to get value out but I started to wonder that I can proabably write this in one line instead. Could you please advice if there is more optimal way to do this?

I am trying to read "123" and "abc" like in Request.QueryString but from normal string.

 protected void Page_Load(object sender, EventArgs e)
{
    string qs = "id=123&xx=abc";
    string[] urlInfo = qs.Split('&');
    string id = urlInfo[urlInfo.Length - 2];
    Response.Write(id.ToString());

}

3 Answers 3

58

You can do it this way:

using System.Collections.Specialized;

NameValueCollection query = HttpUtility.ParseQueryString(queryString);
Response.Write(query["id"]);

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

27

Look at HttpUtility.ParseQueryString. Don't reinvent the wheel.

2 Comments

I knew there had to be better way to do this. I just was looking from wrong place. Thanks!
@jpkeisala- That's the joy of a large framework. It is sometimes hard to find the right class.
3

RichardOD is on it with HttpUtility.ParseQueryString but don't forget to look at TryParse.

You can TryParse int, DateTimes etc

How do you test your Request.QueryString[] variables?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.