29

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?

ChrisP
  • 9,796
  • 21
  • 77
  • 121
  • 5
    ` "+" which doesn't work` Why not? `+` and `%20` should be interpreted the same way by any code that can correctly interpret URL encoding. – Eric J. Sep 09 '15 at 16:29
  • http://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20, http://stackoverflow.com/questions/2678551/when-to-encode-space-to-plus-or-20 – stuartd Sep 09 '15 at 16:37
  • The Yahoo Finance query language doesn't interpret the "+" as equivalent to a space (%20). I tried the URL manually both ways and with the "+" it doesn't work. – ChrisP Sep 09 '15 at 16:39
  • 1
    The URL you have provided returns a valid JSON response with + or %20 (or indeed spaces..) – stuartd Sep 09 '15 at 16:44
  • 2
    @sturatd - JSON is only a small part of the use of UrlEncoding. I am trying to create a mailto tag providing both subject line and body. The WebUtility.UrlEncode is creating a URL with + instead of %20 and as such my mail program displays the plus signs. It does not display the %20. Uri.EscapeUriString does not escape forward slashes correctly. The question by the OP is very much valid and has not yet been answered. – barrypicker Nov 16 '16 at 22:12

3 Answers3

24

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=
Oleks
  • 31,955
  • 11
  • 77
  • 132
9

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

Sasha Kravchuk
  • 161
  • 2
  • 2
0

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);
   }
}
Elon
  • 76
  • 7