System.IO.Exception错误:“请求的操作不能在开放用户映射部分文件上执行。”(Sys

2019-07-01 22:10发布

写一个XML文件时,我收到了,很奇怪的IOException异常:

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)

当我打电话的XmlDocument的Save(串)函数发生错误。

什么任何想法发生了什么?

Answer 1:

看起来像另一过程不得不使用文件映射文件打开(共享存储器)的API。

在Process Explorer的查找功能应该能够告诉你。



Answer 2:

它看起来像你想要写的文件已经打开其他地方,无论是你的代码或其他程序。

你有没有在编辑器中打开该文件? 你有一些其他的代码读取它,但忘记关闭它?

您可以使用进程资源管理器来找出哪个进程上有打开的文件句柄-用Find / Find handle or DLL...命令。



Answer 3:

尝试从项目中排除文件,而调试。 我发现,它实际上是VS2010这是抱着XML文件。 然后,您可以在您的解决方案资源管理器中选择“显示所有文件”,检查XML文件后调试。

这样做的多次写入锁时将停止发行。

lock(file){ write to file code here }


Answer 4:

操作系统或框架可以让你失望,如果你尝试一遍又一遍在紧密循环再次打开相同的文件,例如

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

当然,你并不想真的这样做。 但是,在你的代码中的错误可能导致这种情况发生。 飞机坠毁不是由于你的代码,但与Windows或.NET Framework的一个问题。

如果你必须非常快速地写出大量的文件,你可以添加一个小的延迟与Thread.sleep代码(),这也似乎得到了OS关你的背部。

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


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