mdc
mdc

Reputation: 1201

Replace characters in a string to fit browser, C#, From UTF8 encoding

I need to replace the characters å, ä, ö to browser friendly chars. For example ä should become %E4.

I tried weirdString = Uri.EscapeUriString(weirdString); But it doesnt convert the åäö to the right sign. Help please?

Edit: Tried this:

ASCIIEncoding ascii = new ASCIIEncoding(); 
byte[] asciicharacters = Encoding.UTF8.GetBytes("vägen");
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, asciicharacters);
string finalString = ascii.GetString(asciiArray);
string fixedAddrString = HttpUtility.HtmlEncode(finalString);

Upvotes: 0

Views: 2721

Answers (2)

Oded
Oded

Reputation: 499352

If you need the characters to display on the page and not part of a URL, you should use Server.HtmlEncode.

var encodedString = Server.HtmlEncode(myString); 

HTML encoding makes sure that text is displayed correctly in the browser and not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as the opening or closing bracket of an HTML tag. When the characters are HTML encoded, they are converted to the strings < and >, which causes the browser to display the less than sign and greater than sign correctly.


Update:

Since you are using UTF-8, these characters are escaped to UTF-8, not ASCII.

You need to convert the string from UTF-8 to ASCII, using the Encoding classes before you try to escape them. That is, if you do want the ASCII values to come up.

See here.

Upvotes: 1

NKnusperer
NKnusperer

Reputation: 984

Try HttpUtility.HtmlDecode. If this doesent working too you can do a simple string.Replace for this chars.

Upvotes: 0

Related Questions