How to deal with special characters in ASP.NET's HyperLink.NavigateUrl?
-
06-07-2019 - |
Question
I am currently having troubles figuring out how to handle a filepath to be (dynamicly) passed out to a HyperLink
control's NavigateUrl
property.
Let's say that I'm trying to refer to a file named jäynä.txt
at the root of C:
.
Passing "file:///C:/jäynä.txt"
result to a link to file:///C:/jäynä.txt
, as does HttpUtility.UrlPathEncode("file:///C:/jäynä.txt")
.
Replacing the ä
**s with **%E4
, which gives the string "file:///C:/j%E4yn%E4.txt"
, does give a working link to file:///C:/jäynä.txt
, but I have not been able to find a way to make the replacement without defining it myself. With Replace("ä", "%E4")
, for example.
Is there a way to automaticly handle the filepath string so that the HyperLink
would display it correctly, without manualy listing what characters to replace in the string?
Additional Note:
There may be a way to work around this by spesifying the character encoding in which the page is rendered, because debugging shows that the HyperLink
at least saves the string "file:///C:/jäynä.txt"
unchanged, but somehow mangles it around the time of rendering.
However, this seems only be the case in rendering of the NavigateUrl
because other components as well as HyperLink
's Text
-property are all quite capable of rendering the character ä
unchanged.
Solution
This is due to how the browser starts to interpret the path, typically individuals will avoid using characters such as that in the urls of pages.
In your case, I believe you have struck upon the best case scenario, as I am not aware of any way to change the behavior of HttpUtility and/or the NavigateUrl property. At least not without creating a custom control for it.
OTHER TIPS
The NavigateUrl property of a Hyperlink will encode unicode chars in the url.
Instead you can set the href attribute property of the Hyperlink like this:
hyperlink1.Attribute("href") = "file:///C:/jäynä.txt"
Don't use HyperLink control. Instead use HtmlAnchor control. It will solve your problem. I don't know why Microsoft designed like this.
Thank you! The post using the 'attributes' solved my problem. In my case it was
HyperLink6.Attributes["href"] = "http://høgstedt.danquah.dk/";
The problem of using special danish characters in a url seem to have been troubling a lot of programmers - a search provides several very complicated approaches. This one is SIMPLE and it SIMPLY WORKS. So once again, thank you