0

Our web application uses hyperlinks to reference downloadable documents. An issue recently arose where an apostrophe in the filename was breaking the href link, preventing it from being downloaded.

So I decided to encode the URL with HttpUtility.UrlEncode so that apostrophes are encoded as %27. In the process, spaces were encoded as +'s like so:

http://www.whatever.com/docs/My+Doc+With+Spaces.xls

Whenever the URL is accessed via the link or copied and pasted into Chrome or Firefox's address bar, I get a 404. However, when I manually replace the +'s with a space and hit enter, the document downloads as expected. Oddly, immediately after the download, the URL reverts back to its original format using +'s which results in another 404 when I refresh the browser. Don't get it... the browser doesn't like the +, but then decides that it does?

If I use HttpUtility.UrlPathEncode then it will encode the spaces as %20 which results in a working URL, but it doesn't encode the apostrophe, so I am back at square one.

I need the best of both worlds here.

So my questions are:

  • How can I encode a document filename that has spaces and apostrophes (and all other legal filename characters in a Windows OS)
  • Why won't a hyperlink with +'s work when opened directly? How come when I replace with spaces, the browser reverts it back to use +'s?
oscilatingcretin
  • 10,457
  • 39
  • 119
  • 206
  • I think Uri.EscapeDataString is the method you are looking for – Kevin Aug 09 '17 at 11:58
  • @Kevin That encodes the space as `%20`, but does *not* encode the apostrophe. An answer for https://stackoverflow.com/questions/575440/url-encoding-using-c-sharp suggests that it does, but my results with .NET 4.6.2 show otherwise. – oscilatingcretin Aug 09 '17 at 12:41
  • This point of this whole quesiton could now be moot as the issue might just be with how WebForms assigns URIs to the `href` attribute of a link. When I edit the HTML source with Chrome's inspect, the `'` works fine. What I think I will do is explicitly replace `'` with `%27` in the code. I tried this and it works. – oscilatingcretin Aug 09 '17 at 12:50
  • As the answer below it works for me too... – Kevin Aug 10 '17 at 19:09

1 Answers1

2

I have tried both on .NET 4.5 and .NET 4.6.2

Uri.EscapeDataString("My Doc Wi'th Spaces.xls");

returns My%20Doc%20Wi%27th%20Spaces.xls

Just the value should be the last part of the URL, otherwise ":" and "/" also would be encoded