如何创建在文件系统

时间:2015-04-27 07:03:17

标签: c# winapi events windows-services filesystems

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

1 个答案:

答案 0 :(得分: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
}