How to get part of a url from a string on c #?


Good I would like you to help me I want to get value of a string .              I always want to get the parameter after &VariableR=              Now I'm doing this code but I only get two digits but I'd like to get everything as long as it's after &VariableR= .

string Strings = "";
int indice1 = strings.IndexOf("&VariableR=") + "&VariableR=".Length;
//Resultado me sale 85 
asked by PieroDev 20.07.2018 в 17:49

4 answers


It's as simple as doing:

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

With that you would get the value of param1 for the example URL proposed.

To use the above method you should do: using System.Web;

In your case it would be applied in the following way:

string Strings = "";
Uri theUri = new Uri(Strings);
string paramValue = HttpUtility.ParseQueryString(theUri.Query).Get("VariableR");

If you want to do it a little more generic, you can make it a method:

public static string GetParameterFromUrl(string url, string paramname)
    return HttpUtility.ParseQueryString((new Uri(url)).Query).Get(paramname) ?? null;

And you would call it this way:

string Strings = "";
string VariableR = GetParameterFromUrl(Strings, "VariableR");
Useful links:
answered by 20.07.2018 / 17:56

To do it, as you wish at the string level (as you proposed from the beginning)

string myStrings = "";
int indice1 = myStrings.IndexOf("&VariableR=") + "&VariableR=".Length;

string code = myStrings.Substring(indice1);

With this I would answer your question, but for your case the best option is the one mentioned in another answer, making use of HttpUtility.ParseQueryString

answered by 20.07.2018 в 18:03

Where do I start?

Your code is not bringing you the first two digits. what your code is returning is the length of your string variable to & VariableR that gives the coincidence that it is 85

You were very close to finishing it with this approach, you just had to add the substring:

        string Strings = "";
        int indice1 = Strings.IndexOf("&VariableR=") + "&VariableR=".Length;
        string ValorVariable = Strings.Substring(indice1, (Strings.Length - indice1));

now ... for a better answer:

Are you obtaining the parameters from the browser URL or from a variable?

To get the "Get" parameters of a request you only need to use Request.QueryString

 string ValorVariable = Request.QueryString["VariableR"];
answered by 20.07.2018 в 20:01

You can use the Split function to get this last parameter of your URL.

string Cadena = "";

var param = Cadena.Split('=').Last();


Then to check that you really have this parameter after R = you can use a

if(param != null) Acciones


answered by 20.07.2018 в 18:06