brokencoding
brokencoding

Reputation: 213

XML Writer question

I'm using XML Writer to create a log of some important 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?

Upvotes: 3

Views: 3496

Answers (5)

Al3x_M
Al3x_M

Reputation: 214

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

Upvotes: 0

Binary Worrier
Binary Worrier

Reputation: 51729

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

Upvotes: 1

Mark Milbourne
Mark Milbourne

Reputation: 141

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.

Upvotes: 1

John Saunders
John Saunders

Reputation: 161831

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.

Upvotes: 1

Maurizio Reginelli
Maurizio Reginelli

Reputation: 3222

You can call the method writer.Flush() after your block of instructions. This should write the log and you won't lose any element.

Upvotes: 3

Related Questions