dba*_*baw 6 c# file-io exception
我正在开发一个应用程序,它正在读取和写入很多(但同步)磁盘上的某个文件.但是,文件越大,我就越容易得到以下IOException:
无法对打开了用户映射部分的文件执行请求的操作.
发生于:
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, Int32 bufferSize, FileOptions options)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
at System.IO.File.WriteAllText(String path, String contents, Encoding encoding)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at TestApp.Program.Main()
Run Code Online (Sandbox Code Playgroud)
如您所见,异常从内部抛出File.WriteAllText
.我怀疑异常与同时读写有关,因此试图限制对文件的访问.a lock
和a Mutex
似乎都增加了异常的数量而不是阻止它们.那到底是怎么回事?这个异常究竟意味着什么?如何防止它?
小智 1
我正在写入一个文件(打开,循环(写入),关闭),但在发生错误后,重复了对 rutine 的调用...所以我最终得到“无法在具有用户映射的文件上执行请求的操作”部分打开。”!好吧,我删除了第二个电话,然后问题就解决了。似乎同一个文件上的两个(打开/关闭)(打开/关闭)程序接连发生太快会导致这种情况......一些开发人员建议调用 gc。检查每个 I/O 操作是否正确关闭。不要过早执行完整(打开、循环(写入)、关闭)。似乎当一个操作即将完成时,第二个请求到达并引发问题。