I'm developing an application which checks for changes made to a file by a separate program (not written by me).
If a change is detected, it opens the file, reads the last line, then closes the file.
I'm using the following code to make sure my program doesn't try to lock the file, but only opens it in read mode:
FileStream fs =
new FileStream(
_scannerFilePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs);
va开发者_如何转开发r str = sr.ReadToEnd();
sr.Close();
fs.Close();
Unfortunately, in spite of this, I'm still getting the following error whenever 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 any possible reason for this?
Could it be that the other program is somehow read-locking the file, and thus preventing me from even reading it?
Yes, you can open a file in a so called Exclusive-Mode. This means nobody than yourself can read or write to that file.
If you take a look into the File.Open()
function. There exists a parameter FileShare
which can be set to None
.
精彩评论