Is there a way to write a Stream with FileStream without a BOM? What I am doing here is first converting an XmlNode to a Stream and writing the stream to a file at some point later. I need it to be in the form of a Stream for it to be interoperable with my functions. I could do it an other way, but I want to do it this way if that's possible.
Stream^ XmlToStream(XmlNode^ Node)
{
Stream^ stream = gcnew MemoryStream();
XmlDocument^ xmlDoc = gcnew XmlDocument();
xmlDoc->PreserveWhitespace = true;
xmlDoc->LoadXml(Node->OuterXml);
xmlDoc->Save(stream);
//OR THIS:
//TODO: Handle exceptions
// XmlWriterSettings^ settings = gcnew XmlWriterSettings();
// settings->Encoding = System::Text::Encoding::UTF8;
// settings->OmitXmlDeclaration = true;
// settings->NewLineChars = "\n";
// XmlWriter^ xwriter = XmlWriter::Create(stream, settings);
// Node->WriteTo(xwriter);
// xwriter->Close();
return stream;
}
void StreamToFile(Stream^ DataStream, String^ FilePath)
{
FileStream^ fileStream = gcnew FileStream(FilePath, FileMode::Create);
if (DataStream->CanSeek)
{
DataStream->Seek(0, SeekOrigin::Begin);
}
DataStream->CopyTo(fileStream);
fileStream->Close();
}
You are getting the BOM because by writing to the MemoryStream the framework has no idea what the proper encoding should be. So it punts at the encoding for the XmlDocument, it is utf-8 by default. This gets the BOM generated as well.
To control this, you need to instead pass a TextWriter object to the XmlDocument::Save() method. That can be a StreamWriter which in turn writes to the MS. StreamWriter by default also encodes in utf-8 but does not generate a BOM unless you ask explicitly, just what you want. Like this:
Stream^ XmlToStream(XmlNode^ Node)
{
auto stream = gcnew MemoryStream();
auto writer = gcnew StreamWriter(stream);
//...
xmlDoc->Save(writer);
writer->Flush();
return stream;
}