C#文件被占用的解决方案

时间:2024-04-11 18:43:20

问题

打更新包时,提示文件被占用。

C#文件被占用的解决方案

System.IO.IOException: 文件“D:\RS\RS_CCVI20111210.exe”正由另一进程使用,因此该进程无法访问该文件。
   在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   在 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)
   在 System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   在 System.IO.FileStream..ctor(String path, FileMode mode)
   在 UpdatePack.FileMD5.GetFileMD5(String a_strFileName)
   在 Wesun.WSDM.UpdatePackMgr.Presentation.F102201.PackByReleaseBill.SavePackData(String a_strFileName, String a_strReleaseBillNo)
   在 Wesun.WSDM.UpdatePackMgr.Presentation.F102201.PackByReleaseBill.Pack(String a_strReleaseBillNo, DataTable a_tbFile)
   在 Wesun.WSDM.UpdatePackMgr.Presentation.F102201.FormUpLoad.Btn_okClick(Object sender, EventArgs e)
   在 System.Windows.Forms.Control.OnClick(EventArgs e)
   在 DevExpress.XtraEditors.BaseButton.OnClick(EventArgs e)
   在 DevExpress.XtraEditors.BaseButton.PerformClick()
   在 System.Windows.Forms.Form.ProcessDialogKey(Keys keyData)
   在 System.Windows.Forms.Control.ProcessDialogKey(Keys keyData)
   在 System.Windows.Forms.Control.ProcessDialogKey(Keys keyData)
   在 System.Windows.Forms.Control.PreProcessMessage(Message& msg)
   在 System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
   在 System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)

问题分析

GetFileMD5()这是前同事写的一个获取MD5值的方法,我也不管具体干什么了,具体导致原因“读写文件时文件正由另一进程使用,因此该进程无法访问该文件”。

 

解决方案

1、不单要与只读方式打开txt文件,而且,需要共享锁。还必须要选择flieShare方式为ReadWrite。因为随时有其他程序对其进行写操作。
            // Modify by gyc 2020-11-16 10:30:29 文件被占用,更改为共享方式
//            System.IO.FileStream fs = new System.IO.FileStream(a_strFileName, System.IO.FileMode.Open);
            System.IO.FileStream fs = new System.IO.FileStream(a_strFileName, System.IO.FileMode.Open,
                                                               FileAccess.ReadWrite, FileShare.ReadWrite);
            // End of Modify
 

2、将文件一次加载到内存中,然后读取内存,引入using System.Reflection;

Assembly assembly=Assembly.LoadFile(@文件路径);