c# - 是否可以读取锁定文件?

标签 c# winforms filesystems locking .net

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

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

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

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: 

这有什么可能的原因吗?

会不会是其他程序以某种方式读取锁定文件,从而阻止我读取它?

最佳答案

是的,您可以在所谓的独占模式 中打开文件。这意味着除您之外没有人可以读取或写入该文件。

如果您查看 File.Open()功能。存在参数 FileShare可以设置为 None

关于c# - 是否可以读取锁定文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3254476/

相关文章:

c# - 如何获得当前可用的 Java 版本?

c# - ElasticSearch-字典<对象,对象>的空白分析器

c# - 在 C# 中修改 ComboBox SelectedIndex 而不触发事件

c# - 在 Winforms 应用程序中实现保存并退出

wpf - MVVM 与 Windows 窗体

objective-c - 为什么要将 URL 的书签数据保存到首选项中

c# - C# 中的字符串 "Sort Template"

c++ - 在有人尝试写入文件之前,我如何读取文件?

c++ - 没有内核的 Linux 文件系统

c# - 选择列表更改时如何触发远程验证