55

What exactly is the difference between the two functions. The output seems similar except the Uri.EscapeUriString encodes spaces to %20 and Server.UrlEncode encodes them as a + sign.

And the final question which should be used preferably

5
  • Note that in the title the OP asked about Uri.EscapeDataString and in the question he is asking about Uri.EscapeUriString they a equivalent.
    – It-Z
    Commented May 9, 2016 at 9:15
  • 1
    I posted a detailed answer to a related question here, and in hindsight it might have been a better fit for this question, although I don't want to double post so hopefully linking to it here will suffice. Commented Dec 18, 2017 at 22:51
  • use WebUtility.UrlEncode according to stackoverflow.com/a/47877559/579763
    – Ehsan
    Commented May 15, 2018 at 12:55
  • 1
    I found that HttpUtility.UrlEncode does not change exclamantion marks to %21 but ri.EscapeDataString does!
    – Nick
    Commented Oct 31, 2019 at 11:36
  • gist.github.com/xl1/… Commented Dec 15, 2023 at 22:33

2 Answers 2

37

If any one will came across this in the future:

After some digging I have found out that Uri.EscapeDataString is the preferable option. See the the highest voted answer here and this post.

EDIT: Adding the information from the second link here:

We found that in some cases you need to consider using Uri.EscapeDataString. In our case we are encrypting the querystring and found that UrlDecode is converting a plus (+) to space. This was causing us errors during decryption. Using Uri’s Escape and UnescapeDataString makes sense for us when constructing a custom querystring in the URL.

2
6

I found that HttpUtility.UrlEncode is tolerant to null strings and long strings. It's available both in .NET Core and .NET Framework.

But I also found that Uri.EscapeDataString is 4X faster and uses less memory

Method Mean Error StdDev Gen0 Allocated
EscapeDataString 19.52 ns 0.333 ns 0.018 ns - -
HttpUtilityUrlEncode 88.69 ns 41.303 ns 2.264 ns 0.0191 120 B

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.