Let's say that I have url like http://google.com/index.php?first=asd&second=mnb&third=lkj
How can I get second value (mnb
) using c#?
Let's say that I have url like http://google.com/index.php?first=asd&second=mnb&third=lkj
How can I get second value (mnb
) using c#?
You can use ParseQueryString
method from System.Web.HttpUtility
class.
Uri targetUri = new Uri("http://google.com/index.php?first=asd&second=mnb&third=lkj");
string first= HttpUtility.ParseQueryString(targetUri.Query).Get("first");
string second= HttpUtility.ParseQueryString(targetUri.Query).Get("second");
Find more here : https://msdn.microsoft.com/en-us/library/ms150046.aspx
For simple string parsing you can use an extension method:
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
var value = "url".Between("second=", "&third");
}
}
public static class Ext
{
static string Between(this string source, string left, string right)
{
return Regex.Match(
source,
string.Format("{0}(.*){1}", left, right))
.Groups[1].Value;
}
}
However, approaches with URL parsing suggested in comments are almost certain better.
Try this:
String URL = "http://google.com/index.php?first=asd&second=mnb&third=lkj";
UriBuilder UrlThing = new UriBuilder(URL);
System.Collections.Specialized.NameValueCollection Args = HttpUtility.ParseQueryString(UrlThing.Query);
String Second = Args["Second"];