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

后端 未结 5 839
梦如初夏
梦如初夏 2020-12-03 04:42

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-map         


        
相关标签:
5条回答
  • 2020-12-03 04:54

    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.

    0 讨论(0)
  • 2020-12-03 04:55

    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.

    0 讨论(0)
  • 2020-12-03 05:10

    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.

    0 讨论(0)
  • 2020-12-03 05:15

    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);
     }
    
    0 讨论(0)
  • 2020-12-03 05:18

    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 }
    
    0 讨论(0)
提交回复
热议问题