C A way to analyze URL parameters and get a corresponding list of parameters and values

  • 2021-01-22 05:19:42
  • OfStack

This article illustrates C#'s method of analyzing URL parameters to get a corresponding list of parameters and values. Share with you for your reference. The specific analysis is as follows:

The C# function is used to parse all the arguments passed in url, printing a list of NameValueCollection arguments with their names and values. It is often available


/// <summary>
///  Analysis of the  url  Parameter information in the string 
/// </summary>
/// <param name="url"> The input of  URL</param>
/// <param name="baseUrl"> The output  URL  The foundation of </param>
/// <param name="nvc"> After the output analysis  ( Parameter names , The parameter value )  A collection of </param>
public static void ParseUrl(string url, out string baseUrl, out NameValueCollection nvc)
{
  if (url == null)
 throw new ArgumentNullException("url");
  nvc = new NameValueCollection();
  baseUrl = "";
  if (url == "")
 return;
  int questionMarkIndex = url.IndexOf('?');
  if (questionMarkIndex == -1)
  {
 baseUrl = url;
 return;
  }
  baseUrl = url.Substring(0, questionMarkIndex);
  if (questionMarkIndex == url.Length - 1)
 return;
  string ps = url.Substring(questionMarkIndex + 1);
  //  Start analyzing parameter pairs   
  Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?",RegexOptions.Compiled);
  MatchCollection mc = re.Matches(ps);
  foreach (Match m in mc)
  {
 nvc.Add(m.Result("$2").ToLower(), m.Result("$3"));
  }
}

I hope this article is helpful to your C# program design.


Related articles: