drmaa
drmaa

Reputation: 3684

how to get substring or part of string from a url in c#

I have an application where uses post comments. Security is not an issue. string url = http://example.com/xyz/xyz.html?userid=xyz&comment=Comment

What i want is to extract the userid and comment from above string. I tried and found that i can use IndexOf and Substring to get the desired code BUT what if the userid or comment also has = symbol and & symbol then my IndexOf will return number and my Substring will be wrong. Can you please find me a more suitable way of extracting userid and comment. Thanks.

Upvotes: 1

Views: 2566

Answers (2)

Habib
Habib

Reputation: 223402

I got url using string url = HttpContext.Current.Request.Url.AbsoluteUri;

Do not use AbsoluteUri property , it will give you a string Uri, instead use the Url property directly like:

var result = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);

and then you can extract each parameter like:

Console.WriteLine(result["userid"]);
Console.WriteLine(result["comment"]);

For other cases when you have string uri then do not use string operations, instead use Uri class.

Uri uri = new Uri(@"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment");

You can also use TryCreate method which doesn't throw exception in case of invalid Uri.

Uri uri;
if (!Uri.TryCreate(@"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment", UriKind.RelativeOrAbsolute, out uri))
{
    //Invalid Uri
}

and then you can use System.Web.HttpUtility.ParseQueryString to get query string parameters:

 var result = System.Web.HttpUtility.ParseQueryString(uri.Query);

Upvotes: 5

JGInternational
JGInternational

Reputation: 57

The ugliest way is the following:

String url = "http://example.com/xyz/xyz.html?userid=xyz&comment=Comment";
usr = url.Split('?')[1];
usr= usr.Split('&')[0];
usr = usr.Split('=')[1];

But @habib version is better

Upvotes: 0

Related Questions