3

I develop a simple app, when i try to save an XMLDocument to a thumb drive which doesn't have enough free space, weird thing happens. Though i already added "try catch" clause for XMLDocument.Save(filePath), i still get an unhandled exception, and the exception seems to be thrown from GC finalization thread (seems GC tries to flush another 4096 bytes which the disk does not have). I think it is a common scenario to use XMLDocument object , i wonder what is wrong?

code snippet:

XmlDocument query = new XmlDocument();
query.Load("g:\\test.xml");
... //modify the content of query to make it bigger
try
{
  query.Save("g:\\test.xml");
}
catch(Exception ex)
{}

Exception stacktrace as below:

mscorlib.dll!System.IO.__Error.WinIOError(int errorCode = 112, string maybeFullPath = "") + 0x498 bytes mscorlib.dll!System.IO.FileStream.WriteCore(byte[] buffer, int offset, int count) + 0x119 bytes mscorlib.dll!System.IO.FileStream.FlushWrite(bool calledFromFinalizer) + 0x22 bytes mscorlib.dll!System.IO.FileStream.Dispose(bool disposing = false) + 0x57 bytes
mscorlib.dll!System.IO.FileStream.Finalize() + 0x1b bytes

user1077127
  • 333
  • 1
  • 4
  • 7

1 Answers1

5

Well, the problem is that some code somewhere isn't disposing of the FileStream when it's done with it. When the FileStream is finalized, it's trying to flush the data - at which point the exception is being thrown.

If that really is all of your code, it sounds like it's a bug in XmlDocument.Save(), which should definitely close all its streams before returning. You could work around this by opening the FileStream yourself (with a using statement) and passing the stream to XmlDocument.Save instead.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Thank you so much for ur reply! It works! but does this mean XMLDocument class do have a bug? because i think just fowllow a common scenario to use it. – user1077127 Dec 05 '11 at 09:38
  • 1
    @user1077127: It sounds like it does, yes. I can't say for sure, but it seems odd to me that it doesn't close the stream explicitly. You may want to file a bug on Connect. – Jon Skeet Dec 05 '11 at 09:44