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