XML Writer Question

I use XML Writer to create a log of important events in my application.

Everything is working fine now, assuming the application is closed correctly, but if it is not, the file is not closed and the log is mostly lost.

Suppose a simple element entry is something like this:

 writer.WriteStartElement(eventName);
 writer.WriteAttributeString("t", DateTime.Now.ToString());
 writer.WriteString(eventBody);
 writer.WriteEndElement();

Is there a way to close the file at this point and add the remaining elements to it later and only then close the root element and the XML writer?

+3
source share
5 answers

You can call the writer.Flush () method after your statement block. This should write a log and you will not lose any item.

+3
source

XmlWriter IDisposable. , , Dispose.

, XmLWriterSettings.ConformanceLevel. , XmlWriter, . :

<SomeEvent t="20100228T134000Z">text</SomeEvent>
<SomeOtherEvent t="20100228T134100Z">text</SomeOtherEvent>

.

+1

XmlWriter using;

    using (XmlWriter writer = XmlWriter.Create(stream))
    {
        writer.WriteStartElement("logentry");
        writer.WriteAttributeString("t", DateTime.Now.ToString());
        writer.WriteString("Something to log.");
        writer.WriteEndElement();
    }

, XmlDocumentFragment.

+1

using,

yourXmlWriter.Flush();

yourXmlWriter.Close();

Your data is 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

0
source

Source: https://habr.com/ru/post/1734794/


All Articles