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
31.4k22 gold badges110 silver badges134 bronze badges
asked May 28, 2012 at 12:09
3
  • 3
    This is the correct way though. Commented May 28, 2012 at 12:11
  • So what is the problem? you should use HttpUtility.URLEncode Commented May 28, 2012 at 12:11
  • 1
    So, is there something wrong with string.Replace("+", "%20")? Commented May 28, 2012 at 12:14

3 Answers 3

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?.

answered May 28, 2012 at 12:12
Sign up to request clarification or add additional context in comments.

2 Comments

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'.
What is the minimum required .NET version for HttpUtility.UrlEncode() (not necessarily what is listed in the MSDN page)?
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.

answered May 28, 2012 at 12:13

Comments

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#

answered May 28, 2012 at 12:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.