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

Viewed 74954

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?

5 Answers

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);
 }

In my case, the records in xml document were being iterated and in each iteration the records were being edited and saved. I changed this logic to save the file once after all the records are edited and poofff.. the error is gone.

Related