'How to force %20 instead of + in System.Net.WebUtility.UrlEncode

I need to encode a URL in a class library assembly where I don't want to reference System.Web. The URL contains several spaces

https://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quote where  symbol in ("YHOO","AAPL")&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=

When I use System.Net.WebUtility.UrlEncode() the spaces are replaced with "+" which doesn't work. I need them to be replaced with %20

How can I achieve this without referencing System.Web?



Solution 1:[1]

You could try Uri.EscapeUriString from System assembly, which escapes a URI string. For the string from the question it returns:

https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20%20symbol%20in%20(%22YHOO%22,%22AAPL%22)&format=json&diagnostics=true&env=store%253A%252F%252Fdatatables.org%252Falltableswithkeys&callback=

Solution 2:[2]

Uri.EscapeDataString() is better for you purpose since Uri.EscapeUriString() can skip some special characters

Solution 3:[3]

HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:

NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
   string[] parts = segment.Split('=');
   if (parts.Length > 0)
   {
      string key = parts[0].Trim(new char[] { '?', ' ' });
      string val = parts[1].Trim();

      queryParameters.Add(key, val);
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oleks
Solution 2 Sasha Kravchuk
Solution 3 Elon