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

与世无争的帅哥 提交于 2019-11-27 04:04:30

问题


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?


回答1:


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.




回答2:


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.




回答3:


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 }



回答4:


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


来源:https://stackoverflow.com/questions/1302698/system-io-exception-error-the-requested-operation-cannot-be-performed-on-a-fil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!