XDocument.Save()时的内存exception

我试图将XDcoument保存到没有足够可用内存空间的拇指驱动器。 (这是应用程序的一个特殊测试条件)虽然应用程序给出了如下的exception,但我无法在XDocument.Save(filePath)周围的try catch块中获得该exception。 看起来这是一个延迟投掷。 这是LINQ问题还是我做错了什么?

alt text http://img211.imageshack.us/img211/8324/exce.png

System.IO.IOException was unhandled Message="There is not enough space on the disk.\r\n" Source="mscorlib" StackTrace: at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.WriteCore(Byte[] buffer, Int32 offset, Int32 count) at System.IO.FileStream.FlushWrite(Boolean calledFromFinalizer) at System.IO.FileStream.Dispose(Boolean disposing) at System.IO.FileStream.Finalize() 

您在框架中发现了一个错误。 XDocument.Save(string)使用“using”语句来确保输出流被释放。 它取决于您在处理指令中使用的编码,但内部System.Xml.XmlUtf8RawTextReader是实现文本编写器的常见编码。

错误:编写该类的Microsoft程序员忘记实现Dispose()方法。 只实现了Close()方法。

在connect.microsoft.com反馈网站上尚未报告此错误,这很奇怪。 它应该在一般使用中引起麻烦,因为文件在终结器线程运行之前保持打开状态。 虽然这通常不需要那么长,几秒钟左右。 除非您在写入之后立即退出程序并且在运行磁盘空间时不幸的运气,否则缓冲区将被刷新。

此错误的解决方法是使用XDocument.Save(TextWriter)重载,传递StreamWriter,其Encoding与XML的编码匹配。

查看堆栈跟踪。 这个跟踪以一个Finalize调用开始,该调用执行一个Dispose,它执行一个调用WriteCore的FlushWrite,它会得到错误。

换句话说,首先刷新您的数据。

发布您用来编写的代码,我们可以告诉您在哪里进行刷新。

窥视reflection器,最后几行是

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

这意味着,当处理器被处理时抛出exception。
我想,在调用Save之前检查可用的磁盘空间会更好。

编辑:在调用Save之前,您是否已经Dispose了XDocument实例所依赖的任何对象?

XDocument.Save(string)没有bug,它确实实现了Dispose方法。 使用声明是: – (如上所述)

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

而XmlWriter确实有Dispose() ,它实现了IDisposable接口。