I'm having trouble finding the correct way to URL encode a string in C#. What I want is to encode the string some string
to some%20code
. Using HttpUtility.URLEncode();
method encode is to some+string
.
Asked
Active
Viewed 1.1k times
2

Peter Mortensen
- 30,738
- 21
- 105
- 131

Gregor Menih
- 5,036
- 14
- 44
- 66
-
3This *is* the correct way though. – Konrad Rudolph May 28 '12 at 12:11
-
So what is the problem? you should use HttpUtility.URLEncode – eyossi May 28 '12 at 12:11
-
1So, is there something wrong with `string.Replace("+", "%20")`? – harold May 28 '12 at 12:14
3 Answers
8
HttpUtility.UrlEncode
does the right thing here.
Encodes a URL string. The UrlEncode method can be used to encode the entire URL, including query-string values.
When it comes to spaces on the URL, a +
or %20
are both correct.
-
The problem was that I was sending a HTTP request to get the web page, where '+' was not valid. Eg. Sending a query with 'some+string' would search for 'some+string', not 'some string'. – Gregor Menih May 28 '12 at 14:43
-
What is the minimum required .NET version for HttpUtility.UrlEncode() (not necessarily what is listed in the MSDN page)? – Peter Mortensen May 25 '15 at 19:42
0
If you want spaces encoded as %20
instead of +
, you have to do the encoding yourself.
In URL encoding a +
means space. You can also use %20
, just as you can use the character code variant for any character, but the built in encoding uses the shorter variant.

Guffa
- 687,336
- 108
- 737
- 1,005
0
This thread includes a discussion of some of the in-built encoding options for URIs: