3
我正在開發一個應用程序,用於檢查單獨程序(不是我寫的)對文件所做的更改。是否可以讀取鎖定文件?
如果檢測到更改,它會打開文件,讀取最後一行,然後關閉文件。
我用下面的代碼,以確保我的程序不會嘗試鎖定文件,但只打開它在讀模式:
FileStream fs =
new FileStream(
_scannerFilePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs);
var str = sr.ReadToEnd();
sr.Close();
fs.Close();
不幸的是,儘管如此,我每當我的程序嘗試讀取文件時,仍然會出現以下錯誤:
System.IO.IOException was unhandled
Message="The process cannot access the file 'D:\\LSDATA\\IdText.txt' because it is being used by another process."
Source="mscorlib"
StackTrace:
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 LiquorSafe.Verification.Main.CheckLastScannedUser(String changedFileName)
at LiquorSafe.Verification.Main.OnChanged(Object sender, FileSystemEventArgs e)
at System.IO.FileSystemWatcher.OnChanged(FileSystemEventArgs e)
at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32 action, String name)
at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* overlappedPointer)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
InnerException:
是否有任何可能的原因?
難道是其他程序以某種方式讀鎖定該文件,從而阻止我甚至讀它?