如何检查文件是否打开?

时间:2013-05-23 17:46:59

标签: c# file file-io filelock

我编写程序并需要我自己的文件监视器(循环检查文件是否可以打开)。像这样:

while (loadedFiles.Count > 0 || isNeedReRead)
{
    Thread.Sleep(1000);
    if (isNeedReRead)
        ReadFromRegistry();

    foreach (var file in loadedFiles)
    {
        if (!IsFileLocked(file.Value))
        {
              // logic
        }
    }
}

来源:Is there a way to check if a file is in use?

这是我的解决方案:

try
{
    using (Stream stream = new FileStream(
        path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
    {
        stream.Close();
        return false;
    }
}
catch (IOException)
{
    return true;
}

它适用于Word,Excel。但是如果进程没有锁定文件,这种方法没有帮助。例如,如果打开的位图文件正在更改,IsFileLocked将返回false。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以使用System.IO.FileSystemWatcher设置监控文件,您应该能够使用NotifyFilter属性(设置为LastAccessTime)来检测上次访问特定文件的时间。

void SetupWatcher()
{
    // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"C:\";
    /* Watch for changes in LastAccess and LastWrite times, and
       the renaming of files or directories. */
    watcher.NotifyFilter = NotifyFilters.LastAccess;

    // Only watch text files.
    watcher.Filter = "*.txt";

    // Add event handlers.
    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.Created += new FileSystemEventHandler(OnChanged);
    watcher.Deleted += new FileSystemEventHandler(OnChanged);
    watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;
}

// Define the event handlers. 
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
       Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }

private static void OnRenamed(object source, RenamedEventArgs e)
{
    // Specify what is done when a file is renamed.
    Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}

假设这是另一个选项,Windows是枚举每个进程的打开文件句柄列表。发布的代码here有一个不错的实现,所以你要做的就是调用

DetectOpenFiles.GetOpenFilesEnumerator(processID);

但是,如果进程打开文件将内容读入内存然后关闭文件,您将无法使用监视选项(上面列出),因为一旦读取该进程实际上不再打开该文件进入记忆。