Memory exception while XDocument.Save()

偶尔善良 提交于 2019-12-06 03:19:20

You found a bug in the framework. XDocument.Save(string) uses the "using" statement to ensure the output stream gets disposed. It depends on the encoding you used in the processing instruction but the internal System.Xml.XmlUtf8RawTextReader would be a common one to implement the text writer.

The bug: the Microsoft programmer that wrote that class forgot to implement the Dispose() method. Only the Close() method is implemented.

It is rather strange that this bug wasn't yet reported at the connect.microsoft.com feedback site. It ought to cause trouble in general use because the file stays open until the finalizer thread runs. Although that normally doesn't take that long, a couple of seconds or so. Except in your case where you exit the program right after writing and have the unfortunate luck to run out of disk space at the exact moment the buffer gets flushed.

A workaround for this bug is to use the XDocument.Save(TextWriter) overload instead, passing a StreamWriter whose Encoding matches the encoding of the XML.

Look at the stack trace. This trace starts with a Finalize call, which does a Dispose, which does a FlushWrite, which calls WriteCore, which gets the error.

In other words, flush your data first.

Post the code you use to write and we can show you where to do the flush.

Peeking into reflector, the last few lines are

 using (XmlWriter writer = XmlWriter.Create(fileName, xmlWriterSettings))
 {
     this.Save(writer);
 }

It means, the exception is thrown when the writer is disposed.
I guess, it will be better to check for available disk space before calling Save.

EDIT: Have you Disposed any object that the instance of XDocument depended on before making a call to Save?

Johnny

XDocument.Save(string) does not have a bug, it does implement the Dispose method. The using statement is:- (as also described above)

using (XmlWriter writer = XmlWriter.Create(fileName, xmlWriterSettings)) this.Save(writer);

And XmlWriter does have a Dispose(), it implement the IDisposable interface.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!