How to get% 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. 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 (), spaces are replaced with "+", which does not work. I need to be replaced with% 20

How can I achieve this without reference to System.Web?

+6
source share
2 answers

You can try Uri.EscapeUriString from the System assembly, which eludes the URI string. For a line from a 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= 
+11
source

You could just do this:

 public static string MyUrlEncode(string value) { // Temporarily replace spaces with the literal -SPACE- string url = value.Replace(" ", "-SPACE-"); url = System.Net.WebUtility.UrlEncode(url); // Some servers have issues with ( and ), but UrlEncode doesn't // affect them, so we include those in the encoding as well. return url.Replace("-SPACE-", "%20").Replace("(", "%28").Replace(")", "%29"); } 
+1
source

All Articles