Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a value from a URL query string in C#?

Tags:

c#

regex

Possible Duplicate:
Get individual query parameters from Uri

I have got a URL like this:

http://somedomain.com/website/webpage.aspx?token=123456&language=English

My goal is to extract 123456 from it. There can only be one payment ID in the query-string parameter. What kind of regular expression can I use? I am using C# (.NET) by the way.

Thanks

like image 712
Varun Sharma Avatar asked Jan 30 '26 16:01

Varun Sharma


1 Answers

Use System.URI class

The Query property of the URI class returns the entire query as a string

Uri bUri = new Uri("http://somedomain.com/website/webpage.aspx
                    ?token=123456&language=English");

var query = bUri.Query.Replace("?", "");

Now query will have the string value "token=123456&language=English"

Then use LINQ to produce a Dictionary from the query attributes

var queryValues = query.Split('&').Select(q => q.Split('='))
                   .ToDictionary(k => k[0], v => v[1]);

You can then access the values as

queryValues["token"]

which will give you 123456

like image 180
Prabhu Murthy Avatar answered Feb 02 '26 05:02

Prabhu Murthy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!