Reputation: 514
I am trying to open an xml file in browser and I get the following error:
Switch from current encoding to specified encoding not supported. Error processing resource
Now I am generating this XML using C# by the code below. My XML has latin characters so I want to have encoding as ISO-8859-1 and not utf-16. But each time my xml generate, it take encoding as utf-16 and not ISO-8859-1. I would like to know what is the cause and resolution.
Note: I only need ISO-8859-1 and not utf-8 or utf-16 as the XML is getting generated properly if the encode is ISO-8859-1.
C# code:
var doc = new XDocument(new XDeclaration("1.0", "iso-8859-1", "yes"),new XElement("webapp", new XAttribute("name", webApp.Name), new XAttribute("id", webApp.Id), Myinformation());
var wr= new StringWriter();
doc.Save(wr);
return wr.ToString();
Upvotes: 1
Views: 4999
Reputation: 26213
A string, conceptually at least, doesn't have an encoding. It's just a sequence of unicode characters. That said, a string in memory is essentially UTF-16, hence StringWriter
returns that from its Encoding
property.
What you need is a writer that specifies the encoding you want:
var doc = new XDocument(new XElement("root"));
byte[] bytes;
var isoEncoding = Encoding.GetEncoding("ISO-8859-1");
var settings = new XmlWriterSettings
{
Indent = true,
Encoding = isoEncoding
};
using (var ms = new MemoryStream())
{
using (var writer = XmlWriter.Create(ms, settings))
{
doc.Save(writer);
}
bytes = ms.ToArray();
}
This will give you the binary data encoded using ISO-8859-1, and as a consequence the declaration will specify that encoding.
You can convert this back to a string:
var text = isoEncoding.GetString(bytes);
But note that this is no longer encoded in ISO-8859-1, it's just a string again. You could very easily encode it using something else and your declaration would be incorrect.
If you're sure you want this as an intermediate string, then I'd suggest you use the approach in this answer.
Upvotes: 2