Question

How did you get ASP.NET to output UTF-16 encoded text?

I serialize an object in .NET which by default is UTF-16 format. Now I want to send the string as an output response to an .ashx request.

I get the error: Switch from current encoding to specified encoding not supported. Error processing resource

How do I tell my website or page to use UTF-16 format.

Thanks.

Update: read both answers.

Was it helpful?

Solution

In general: don't.

Web pages as UTF-16 confuse many tools and make browsers behave in odd, unexpected ways. (Esp.: linked scripts, form submissions, proxies). UTF-16 can only be served safely as a binary object, so for web content stick to an encoding that is a superset of ASCII - the obvious choice being UTF-8.

The error you quote is generally what you get when you try to read an XML file whose <?xml encoding="..."?> prolog clashes with the real encoding of the file. None of the superset-of-ASCII encodings ever clash because 'xml encoding' is ASCII and represented the same in all of them, but if you've put encoding="utf-16" in an XML file that's not saved as UTF-16, or you've not put it in when it is, then the parser can't cope with the logical impossibility.

OTHER TIPS

The following worked for me:

Dim utf16 = New UnicodeEncoding(False, True)
Response.BinaryWrite(utf16.GetPreamble)
Response.ContentEncoding = utf16

By the way, I needed to do this because I was sending an html table which contained unicode characters to Excel. (I know, not the best way to create an Excel file!)

Excel (and LibreOffice Calc) expects utf-16 and doesn't work with utf-8. Excel also needs the UTF16 BOM at the beginning, hence the call to GetPreamble.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top