C# – Get URL parameters from a string in .NET

.netc++parametersparsingurl

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);

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?

Best Solution

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