【问题标题】:How to create an event which fires after any file is modified or created or deleted in the filesystem如何创建在文件系统中修改或创建或删除任何文件后触发的事件
【发布时间】:2015-04-27 07:03:16
【问题描述】:

我想创建一个 Windows 服务,它检测是否对文件系统中的任何文件进行了任何更改(创建、删除或修改)。 当它检测到更改时,我会检查是否对相关文件进行了更改。如果是这种情况,那么我会将文件同步到服务器。 我知道我将如何同步文件,我只想知道如何创建一个在文件系统发生任何更改时触发的事件。 该事件还应提供有关被修改文件的路径、对文件执行的操作等信息。

【问题讨论】:

  • 看看这个答案:stackoverflow.com/questions/931093/… 它还描述了 C# .Net 方式
  • Directory Modification Monitoring 的可能副本。 注意: 这主要是对那个问题的欺骗。但是,请记住:FSW 不保证您会收到通知,如果给定文件系统上的活动很高,它会错过一些。您要监控的文件系统越多(例如“文件系统中的任何文件”),FSW 就越有可能遗漏某些内容。

标签: c# winapi events windows-services filesystems


【解决方案1】:

你只需要初始化FileSystemWatcher并订阅相关事件。

FileSystemWatcher watcher = new FileSystemWatcher(@"DirectoryPath");
watcher.Filter = "*.*";//Watch all the files
watcher.EnableRaisingEvents = true;

//Specifies changes to watch for in a file or folder.
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;

//订阅以下活动

watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Created += new FileSystemEventHandler(watcher_Created);
watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);

//Raise when new file is created
private void watcher_Created(object sender, FileSystemEventArgs e)
{
  //Sync with server
}

//Raise when file is modified
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
  //Sync with server
}    

//Raise when a file is deleted
private void watcher_Deleted(object sender, FileSystemEventArgs e)
{
  //Sync with server
}

【讨论】:

  • 感谢您的解决方案稍作修改。 >>代替目录路径,我写了“D:\”来搜索整个驱动​​器。 >>watcher.IncludeSubdirectories = true;这样 wacher 也可以搜索子目录。
  • @VK 很高兴它帮助了你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 2019-01-04
相关资源
最近更新 更多