I want to save the complete result of a FOR XML
SQL Query to a file.
My SQL Query looks something like this:
SELECT * FROM Customer FOR XML RAW
in my code, I now want to execute this query against an SQL Server and read the complete XML result and save it to disk.
My code looks like this:
using (XmlReader xmlResultReader = command.ExecuteXmlReader()) //command is my SqlCommand
using (MemoryStream resultFile = new MemoryStream())
using (StreamWriter writer = new StreamWriter(resultFile, Encoding.UTF8))
{
while (xmlResultReader.Read())
{
writer.WriteLine(xmlResultReader.ReadOuterXml());
}
//write stream to file
}
But when I run this, not the complete result of the query gets saved to the MemoryStream
. The result is truncated in the middle of a <row />
element in the resulting XML. So not even the returned XML is valid.
I also tried writing the result with an XmlWriter
using this code:
xmlWriter.WriteNode(xmlResultReader, false);
but this showed the same result.
So now my question is: How can I get the complete XML result of the query from the XmlReader
returned by ExecuteXmlReader()
?