gpt4 book ai didi

c# - FileSystemWatcher 用于监视打开的文件夹/文件

转载 作者:太空狗 更新时间:2023-10-29 21:50:52 31 4
gpt4 key购买 nike

我浏览了一圈,但找不到任何关于我正在寻找的信息,如果有另一篇文章已经讨论过这个问题,那么我深表歉意。

我正在寻求有关代码的帮助,这些代码将监视特定文件夹何时被其他人打开该文件夹或何时打开该文件夹下的文件。此时我可以看到用户何时打开和修改任何文件,但如果他们只是打开文件查看它,即使我添加了 LastAccessed,它也不会引发事件。任何信息或帮助将不胜感激。

文件夹名称是 C:\Junk

C# 4.0 中的代码:

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{


FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "junk";

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

// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}

// 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);
}

最佳答案

it does not throw an event even when I add LastAccessed.

因为 NotifyFilters.LastAccessed指定您希望检索该属性,而不是要订阅的事件。可用的事件是 Changed , Created , 或 Deleted ,没有一个能满足您的需求。

你应该看看 ReadDirectoryChangesW Win32 函数,已记录 here .它可以传递 FILE_NOTIFY_CHANGE_LAST_ACCESS标志,它似乎提供了你想要的东西:

Any change to the last access time of files in the watched directory or subtree causes a change notification wait operation to return.

编辑:忽略这个,FileSystemWatcher内部通过 NotifyFilters.LastWrite作为 int 32,与 FILE_NOTIFY_CHANGE_LAST_ACCESS 相同, 至 ReadDirectoryChangesW .然后该函数仍然不会通知文件访问,我试过了。

也许这是由 this 引起的:

Last Access Time has a loose granularity that only guarantees that the time is accurate to within one hour. In Windows Vista, we've disabled updates to Last Access Time to improve NTFS performance. If you are using an application that relies on this value, you can enable it using the following command:

fsutil behavior set disablelastaccess 0

You must restart the computer for this change to take effect.

如果您在命令提示符下执行它,那么可能会出现 LastAccess将被写入并且事件将触发。我不打算在我的 SSD 上试用,也没有准备好 VM,但在 Windows 7 上 disablelastaccess似乎是开箱即用的。

如果禁用该行为后仍然不起作用,请等待 Raymond Chen(或他自己)的建议框出现,通常会有一个非常合乎逻辑的解释说明为什么文档似乎没有正确描述您遇到的行为. ;-)

您也可以循环扫描目录并查看文件的 LastAccessed 属性。 用户打开某个文件时,您想要做什么?

关于c# - FileSystemWatcher 用于监视打开的文件夹/文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14779616/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com