1

I want to count how many query string key appear in a string of URL. The URL here is an string so I can't use Request.QueryString.AllKeys to count how many key in the url. Currently, I have an solution for this by analyze the structure of url string and using count string within a string to count query string keys in an url string. Everyone can look clearly in my sample of code:

public int CountQueryStringKey(string urlString)
{
    string urlWithoutKey = urlString.Substring(0, urlString.IndexOf("?"));
    string allKeyString = urlString.Substring(urlString.IndexOf("?") + 1);
    string[] allKeyAndValue = allKeyString.Split('&');
    return allKeyAndValue.Length;
}

It is simple but not enough. What will happen if there is no query string key in string of url, and there are always different kind of url which I'm not sure it's structure.

I need some help for a good solution in this issue.

Tri Nguyen Dung
  • 929
  • 2
  • 13
  • 24
  • Also, it is possible to use a different separation character. – Bart Friederichs Mar 05 '13 at 07:08
  • 1
    possible duplicate of [Get individual query parameters from Uri](http://stackoverflow.com/questions/2884551/get-individual-query-parameters-from-uri) – Alexei Levenkov Mar 05 '13 at 07:09
  • My sample code is not a good solution. May be I can add string of url into an Uri like this: Uri uri = new Uri(urlString), and then do a request.QueryString to count. It will be better. – Tri Nguyen Dung Mar 05 '13 at 07:14

2 Answers2

2

While duplicate (Get individual query parameters from Uri) provides good enough answer I'd suggest using Uri.Query to extract query portion of the Url. Than continue with HttpUtility.ParseQueryString as recommended in other question. Than NameValueCollection.Count to get the number of query parameters.

var queryParameters = HttpUtility.ParseQueryString(new Uri(urlString).Query);
var numberOfParameter = queryParameters.Count;
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
1

Have a look at this post. Here you can use HttpUtility to get query string parameters from the normal string

HttpUtility

K D
  • 5,889
  • 1
  • 23
  • 35