misak misak - 3 months ago 21
C# Question

How to correct parse query string in C# if value contains ampersand?

I need parse query string:

?artist=singer1 & singer2&song=name song


Static method
HttpUtility.ParseQueryString
doesn't work the way I want if value contains ampersand like "singer1 & singer2".

For example:

string qs = "?artist=singer1 & singer2&song=name song";
NameValueCollection query = HttpUtility.ParseQueryString(qs);


Result is:



  1. artist = singer1

  2. null = singer2

  3. song = name song




I would like result

artist = singer 1 & singer2
song = name song


Any idea?

Answer

The ampersand (&) in the middle of one of your values is throwing off the parser since it's a reserved symbol. Replace it with its numeric code instead:

string qs = "?artist=singer1+%26+singer2&song=name song"; 
NameValueCollection query = HttpUtility.ParseQueryString(qs);