views:

3387

answers:

2

I received a very weird IOException when writing to an XML file:

System.IO.IOException: The requested operation cannot be performed on a file with a user-mapped section open.

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.Xml.XmlTextWriter..ctor(String filename, Encoding encoding)
   at System.Xml.XmlDocument.Save(String filename)

The error happened when I called XmlDocument's Save(string) function.

Any ideas on what happened?

+2  A: 

Looks like another process had the file open using the file mapping (shared memory) APIs.

The find function in Process Explorer should be able to tell you.

Richard
It could also be transient (just happened to me, next write attempt was fine but I failed on the next file, which then worked fine on next attempt), like when an antivirus scanner is rocking through your world.
dash-tom-bang
+2  A: 

It looks like the file you're trying to write is already open elsewhere, either by your code or by another process.

Do you have the file open in an editor? Do you have some other code that reads it, but forgets to close it?

You can use Process Explorer to find out which process has open file handle on it - use the Find / Find handle or DLL... command.

RichieHindle