Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 可以读取锁定文件吗?_C#_Winforms_Filesystems_Locking_.net - Fatal编程技术网

C# 可以读取锁定文件吗?

C# 可以读取锁定文件吗?,c#,winforms,filesystems,locking,.net,C#,Winforms,Filesystems,Locking,.net,我正在开发一个应用程序,用于检查由单独的程序(不是由我编写的)对文件所做的更改 如果检测到更改,它将打开文件,读取最后一行,然后关闭文件 我使用以下代码来确保我的程序不会尝试锁定文件,而只是在读取模式下打开它: FileStream fs = new FileStream( _scannerFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Stre

我正在开发一个应用程序,用于检查由单独的程序(不是由我编写的)对文件所做的更改

如果检测到更改,它将打开文件,读取最后一行,然后关闭文件

我使用以下代码来确保我的程序不会尝试锁定文件,而只是在读取模式下打开它:

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: 
有什么可能的原因吗


是否另一个程序以某种方式对文件进行了读取锁定,从而阻止了我读取该文件?

是的,您可以以所谓的独占模式打开文件。这意味着除了您自己,没有人可以读或写该文件

如果你看看这个函数。存在一个可设置为
None
的参数