49

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

gotqn
  • 42,737
  • 46
  • 157
  • 243
RC1140
  • 8,423
  • 14
  • 48
  • 71
  • 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 May 09 '16 at 09:15
  • I posted a detailed answer to a related question [here](https://stackoverflow.com/a/47877559/62600), 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. – Todd Menier Dec 18 '17 at 22:51
  • use WebUtility.UrlEncode according to https://stackoverflow.com/a/47877559/579763 – Ehsan May 15 '18 at 12:55
  • 1
    I found that HttpUtility.UrlEncode does not change exclamantion marks to %21 but ri.EscapeDataString does! – Nick Oct 31 '19 at 11:36

2 Answers2

35

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.

It-Z
  • 1,961
  • 1
  • 23
  • 33
4

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
Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149