I need to serialise some objects to a blob to pass in to a web service call. All pretty basic stuff.
The nub of the problem is that the snippet of code that does the work is pretty inflexible in that when using a StringWriter, the encoding of the output is always UTF-16
StringWriter stringWriter = new StringWriter();
serialiser.Serialize(stringWriter, Container.Calls);
string data = stringWriter.ToString();
That handles most scenarios but I want to make this as generic as possible & deal with other encodings so I changed the above to this (with the idea that I could refactor and pass in the encoding at a later time):
XmlTextWriter xmlTextWriter = new XmlTextWriter(stream,Encoding.Unicode);
serialiser.Serialize(xmlTextWriter, Container.Calls);
byte[] bytes = stream.GetBuffer();
string data = System.Text.Encoding.Unicode.GetString(bytes);
System.Text.Encoding.Unicode.GetString no longer returns valid xml as there is a Byte Order Mark at the start of the stream. I could call stream.Read and specify the offset of the BOM but, dependinmg on the encoding, I don't always expect it to be present so this could get messy. What I really need is for it not to be there at all.