I am working on a client application that uses the recovery service to search for companies by name. It is very important that ampersand literals are included in my queries, as this character is quite common in company names.
However, whenever I pass% 26 (URI with an ampersand character) to System.Uri , it will convert it back to a regular ampersand character! On closer inspection, only two characters that were not returned are the hash (% 23) and the percentage (% 25).
Suppose I want to find a company called Pier and Pier:
var endPoint = "http://localhost/companies?where=Name eq '{0}'"; var name = "Pierce & Pierce"; Console.WriteLine(new Uri(string.Format(endPoint, name))); Console.WriteLine(new Uri(string.Format(endPoint, name.Replace("&", "%26")))); Console.WriteLine(new Uri(string.Format(endPoint, Uri.EscapeUriString(name)))); Console.WriteLine(new Uri(string.Format(endPoint, Uri.EscapeDataString(name))));
All four of the above combinations return:
http://localhost/companies?where=Name eq 'Pierce & Pierce'
This causes server-side errors because the ampersand is (correctly) interpreted as a delimiter of the request arguments. I really need to return the original string:
http://localhost/companies?where=Name eq 'Pierce %26 Pierce'
How can I get around this behavior without completely dropping System.Uri ? I cannot replace all ampersands with% 26 at the last moment, because usually several query arguments will be involved, and I do not want to destroy their delimiters.
Note. . A similar problem was discussed in this question , but I specifically refer to System.Uri .