【问题标题】:How to use FileSystemWatcher to check whether a file is locked by another process? [duplicate]如何使用 FileSystemWatcher 检查文件是否被另一个进程锁定? [复制]
【发布时间】:2013-01-09 03:03:43
【问题描述】:

可能重复:
Wait until file is unlocked in .NET

在很多情况下,程序必须等到文件被另一个进程解锁(例如正在复制的文件)才能再次使用它。一个标准的解决方案是等待它使用 Thread.Sleep() 在循环中迭代。我不认为这种好。我已经读过可以使用 .NET 的 FileSystemWatcher 来做到这一点(我使用的是 C#)。任何人都可以说明吗?非常感谢您的回复!

【问题讨论】:

  • 没有。 FileSystemWatcher 不会告诉您何时释放文件句柄。
  • 但是如果创建了文件,它会触发一个 sertain 事件。这不能解决我的问题吗?
  • 解锁的文件与创建的文件不同。
  • 在一般情况下,即使您可以找到一种方法来通知文件已解锁,但在您的代码运行并尝试获取文件时,可能会有一些其他进程获得了新的锁。您必须编写代码,以便在您尝试获取文件时无论如何对被锁定的文件做出反应。
  • 如果另一个进程在程序运行时获得了新的锁,可以避免干扰注销事件:codewatcher.EnableRaisingEvents = false;code

标签: c# .net filesystemwatcher


【解决方案1】:

FileSystemWatcher 顾名思义,让您监视当您change,create,delete,rename 文件或文件夹时发生的任何事件

您不能使用FileSystemWatcher 来检查文件是否被锁定..

【讨论】:

    【解决方案2】:
    FileSystemWatcher _watcher;
    int _watcherEventFiredCounter;
    
    _watcher = new FileSystemWatcher {
        Path = @"C:\temp",
        NotifyFilter = NotifyFilters.LastWrite,
        Filter = "*.zip",
        EnableRaisingEvents = true
    };
    
    _watcher.Changed += OnChanged;
    
    
    private void OnChanged(object sender, FileSystemEventArgs e)
    {
        _watcherEventFiredCounter++;
        // The event is fired two times: on start copying and on finish copying
        if (_watcherEventFiredCounter == 2) {
            Console.WriteLine("Copying is finished now!");
            _watcherEventCounter = 0;
        }
    }
    

    现在的问题是如何回到调用线程?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 2012-03-09
    相关资源
    最近更新 更多