1

我编写了程序并且需要我自己的文件观察器(检查文件是否可以打开的循环)。像这样的东西:

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

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

资料来源:有没有办法检查文件是否正在使用?

这是我的解决方案:

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。

有任何想法吗?

4

1 回答 1

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 的另一个选项是枚举每个进程的打开文件句柄列表。这里发布的代码有一个不错的实现,所以你所要做的就是调用

DetectOpenFiles.GetOpenFilesEnumerator(processID);

但是,如果一个进程打开一个文件,然后将其内容读入内存,然后关闭该文件,您将无法使用监控选项(如上所列),因为一旦将文件读入内存,该进程实际上就不再打开该文件。

于 2013-05-23T18:04:07.870 回答