2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gregor Menih
  • 5,036
  • 14
  • 44
  • 66

3 Answers3

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.

Also see URL encoding the space character: + or %20?.

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 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:

How do I replace all the spaces with %20 in C#

Community
  • 1
  • 1
Dave R.
  • 7,206
  • 3
  • 30
  • 52