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

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?


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.


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.


Try excluding the file from your project while you debug. I found that it was in fact VS2010 which was holding the XML file. You can then select "Show all files" in your solution explorer to check the XML file post debug.

A lock will stop the issue when doing multiple writes.

lock(file){ write to file code here }

The OS or Framework can fail you, if you try to open the same file over and over again in a tight loop, for example

 while (true) {
   File.WriteAllLines(...)
 }

Of course, you don't want to actually do that. But a bug in your code might cause that to happen. The crash is not due to your code, but a problem with Windows or the .NET Framework.

If you have to write lots of files very quickly, you could add a small delay with Thread.Sleep() which also seems to get the OS off your back.

 while (i++<100000000) {
   File.WriteAllLines(...)
   Thread.Sleep(1);
 }