I'm using XML Writer to create a log of some important 开发者_C百科events in my application.
Currently it all works fine assuming that the application is correctly closed, but if it isnt, the file isnt closed and the log is basically lost.
Let's assume the writing of a simple element, something like this:
writer.WriteStartElement(eventName);
writer.WriteAttributeString("t", DateTime.Now.ToString());
writer.WriteString(eventBody);
writer.WriteEndElement();
Is there any way to close the file at this point and append the remaining elements to it later and only then closing the root element and xml writer?
You can call the method writer.Flush() after your block of instructions. This should write the log and you won't lose any element.
The XmlWriter
class implements the IDisposable
interface. That means you must ensure that the Dispose
method is called on your instance.
In addition, you should see the example at XmLWriterSettings.ConformanceLevel
. It shows how to create an XmlWriter
which is ok with writing a fragment. You can write a document with one log entry per element:
<SomeEvent t="20100228T134000Z">text</SomeEvent>
<SomeOtherEvent t="20100228T134100Z">text</SomeOtherEvent>
Just be sure to flush the writer after each.
Put your XmlWriter in a using statement;
using (XmlWriter writer = XmlWriter.Create(stream))
{
writer.WriteStartElement("logentry");
writer.WriteAttributeString("t", DateTime.Now.ToString());
writer.WriteString("Something to log.");
writer.WriteEndElement();
}
You'll probably have to do some XmlDocumentFragment tricks also.
See the first topic on this page, basically shows how to keep an XML log file without worrying about keeping the file open, and without worrying about what to do with the closing tag too. Hope you find it useful.
http://msdn.microsoft.com/en-us/library/aa302289.aspx
If you don't use the using statement, you need to use a function like
yourXmlWriter.Flush();
or
yourXmlWriter.Close();
Your datas are still in the buffer and you need to write to the underlying stream. (Could be a file or any stream...)
https://msdn.microsoft.com/en-us/library/system.xml.xmlwriter(v=vs.110).aspx
精彩评论