Beska Beska - 1 year ago 218
C# Question

Get url parameters from a string in .NET

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

, but this string isn't from the request. I can create a new
item like so:

Uri myUri = new Uri(TheStringUrlIWantMyValueFrom);

I can use
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?

Answer Source

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

Uri myUri = new Uri("");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");

Check documentation at

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download