ASP.Net URLEncode Ampersand for use in Query String

The documentation suggests that Server.UrlEncode should handle ampersands correctly.

I've just tested your exact code and the returned string was correctly encoded:

http://www.example.com/?Value=This+%26+That


Technically doing:

value = value.Replace("&", "%26") 

will do the trick.

EDIT: There seem to be some tricky issues with the whole UrlEncode/HttpEncode methods that don't quite do the trick. I wrote up a simple method a while back that may come in handy. This should cover all the major encoding issues, and its easy to write a "desanitizer" as well.

Protected Function SanitizeURLString(ByVal RawURLParameter As String) As String

      Dim Results As String

      Results = RawURLParameter    

      Results = Results.Replace("%", "%25")
      Results = Results.Replace("<", "%3C")
      Results = Results.Replace(">", "%3E")
      Results = Results.Replace("#", "%23")
      Results = Results.Replace("{", "%7B")
      Results = Results.Replace("}", "%7D")
      Results = Results.Replace("|", "%7C")
      Results = Results.Replace("\", "%5C")
      Results = Results.Replace("^", "%5E")
      Results = Results.Replace("~", "%7E")
      Results = Results.Replace("[", "%5B")
      Results = Results.Replace("]", "%5D")
      Results = Results.Replace("`", "%60")
      Results = Results.Replace(";", "%3B")
      Results = Results.Replace("/", "%2F")
      Results = Results.Replace("?", "%3F")
      Results = Results.Replace(":", "%3A")
      Results = Results.Replace("@", "%40")
      Results = Results.Replace("=", "%3D")
      Results = Results.Replace("&", "%26")
      Results = Results.Replace("$", "%24")

      Return Results

End Function