Both methods show the space as
+
, so you can replace
+
with
%20
after using
UrlEncode
:
string yourStr = "your text here";
string encodedStr = HttpUtility.UrlEncode(yourStr).Replace("+", "%20");
If the above method doesn't encode enough chars, as you said in your comment, use this function:
string UrlEncode(string url)
{
Dictionary<string, string> toBeEncoded = new Dictionary<string, string>() { { "%", "%25" }, { "!", "%21" }, { "#", "%23" }, { " ", "%20" },
{ "$", "%24" }, { "&", "%26" }, { "'", "%27" }, { "(", "%28" }, { ")", "%29" }, { "*", "%2A" }, { "+", "%2B" }, { ",", "%2C" },
{ "/", "%2F" }, { ":", "%3A" }, { ";", "%3B" }, { "=", "%3D" }, { "?", "%3F" }, { "@", "%40" }, { "[", "%5B" }, { "]", "%5D" } };
Regex replaceRegex = new Regex(@"[%!# $&'()*+,/:;=?@\[\]]");
MatchEvaluator matchEval = match => toBeEncoded[match.Value];
string encoded = replaceRegex.Replace(url, matchEval);
return encoded;
}
And to encode the URL:
string yourStr = "your text here";
string encodedStr = UrlEncode(yourStr);