views:

2306

answers:

4

Okay, this is probably a simple one...

I've got a string in .NET which is actually a url. I want an easy way to get the value from a particular parameter.

Normally, I'd just use Request.Params["theThingIWant"], but this string isn't from the request. I can create a new Uri item like so:

Uri myUri = new Uri(TheStringUrlIWantMyValueFrom);

And I can use myUri.Query to get the query string...but then I apparently have to find some regexy way of splitting it up.

Am I missing something obvious, or is there no built in way to do this short of creating a regex of some kind, etc?

+4  A: 

Looks like you should loop over the values of myUri.Query and parse it from there.

 string desiredValue;
 foreach(string item in myUri.Query.Split('&'))
 {
     string[] parts = item.Replace('?', '').Split('=');
     if(parts[0] == "desiredKey")
     {
      desiredValue = parts[1];
      break;
     }
 }

I wouldn't use this code without testing it on a bunch of malformed URL's however. It might break on some/all of these:

  • hello.html?
  • hello.html?valuelesskey
  • hello.html?key=value=hi
  • hello.html?hi=value?&b=c
  • etc
Tom Ritter
+25  A: 

Use static ParseQueryString() method of System.Web.HttpUtility class that returns NameValueCollection.

Uri myUri = new Uri("http://www.example.com?param1=good&param2=bad");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");

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

CZFox
Boom! Quick way to raise your rep up! Thanks!
Beska
You are welcome.
CZFox
Andrew Shepherd
A: 

Use .Net Reflector to view the "FillFromString" method of System.Web.HttpValueCollection. That gives you the code that ASP.Net is using to fill the Request.QueryString collection.

David
+4  A: 

This is probably what you want

var uri = new Uri("http://domain.test/Default.aspx?var1=true&var2=test&var3=3");
var query = HttpUtility.ParseQueryString(uri.Query);

var var2 = query.Get("var2");
Sergej Andrejev