I am developing an application that checks for changes made to a file in a separate program (not written by me).
If a change is detected, it opens the file, reads the last line and closes the file.
I use the following code to make sure that my program does not try to lock the file, but opens it only in read mode:
FileStream fs =
new FileStream(
_scannerFilePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs);
var str = sr.ReadToEnd();
sr.Close();
fs.Close();
Unfortunately, despite this, I still get the following error when my program tries to read the file:
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:
Is there a possible reason for this?
Could it be that another program is in some way a read-locking file and thus prevents me from even reading it?