1

It definitely has been asked many times, but offered solutions does not seem to work.

Input:

sample text

Output:

sample%20text

I'm using suggested HttpUtility.UrlEncode() but instead of desired output it returns:

sample+text

Am i doing something wrong, or this method is no longer valid?

AdmiralCat3
  • 99
  • 1
  • 6
  • 1
    Does this answer your question? [How do I replace all the spaces with %20 in C#?](https://stackoverflow.com/questions/1517586/how-do-i-replace-all-the-spaces-with-20-in-c) Here is [Explanation](https://stackoverflow.com/questions/2678551/when-to-encode-space-to-plus-or-20) for `+` and `%20` for spaces – Pavel Anikhouski Jun 22 '20 at 14:47
  • 1
    If the string goes into a query parameter (or a POST form body - anything with MIME type `application/x-www-form-urlencoded`), then `+` is actually a valid (and often-used) encoding for a space. (However, if it goes into the path portion, you do need `%20`.) – CherryDT Jun 22 '20 at 14:48
  • 1
    Also, the remarks for `Http.UrlEncode` in the [docs](https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.urlencode?view=netcore-3.1) explain that too, and that you can use `Http.UrlPathEncode` for the case where you need `%20` instead of `+`. – CherryDT Jun 22 '20 at 14:49

1 Answers1

4

Try this:

string str = "sample text";
string url = Uri.EscapeDataString(str);
kumi95
  • 81
  • 4