Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

c# - Is it possible to read-lock a file?

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);
var 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...