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

守給你的承諾、 提交于 2020-01-06 03:32:06

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/30669404/how-to-get-substring-or-part-of-string-from-a-url-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!