C#读写文件时出现占用的解决办法2
打更新包时,提示文件被占用。

System.IO.IOException: 文件“****.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)
……
问题分析
具体导致原因“读写文件时文件正由另一进程使用,因此该进程无法访问该文件”。
解决方案
1、不单要与只读方式打开txt文件,而且,需要共享锁。还必须要选择flieShare方式为ReadWrite。因为随时有其他程序对其进行写操作。
// Modify by log 2022-11-14 14:40:10 文件被占用,更改为共享方式
// 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.Read, FileShare.ReadWrite);
// End of Modify
2、将文件一次加载到内存中,然后读取内存,引入using System.Reflection;
Assembly assembly=Assembly.LoadFile(@文件路径);
posted on 2022-11-14 15:16 8888888888888 阅读(2181) 评论(1) 收藏 举报
浙公网安备 33010602011771号