2015-04-27 70 views
0

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

+0

看看这个答案:http://stackoverflow.com/questions/931093/how-do-i-make -my-program-watch-for-file-modification-in-c它也描述了C#.Net方式 –

+0

[Directory Modification Monitoring]的可能重复(http://stackoverflow.com/questions/112276/directory-modification-监测)。 **注意:**这大多是这个问题的一个骗局。但是,请记住:FSW并不保证您会收到通知,并且如果在给定的文件系统上活动很高,则会漏掉一些。要监视的文件系统越多(例如“文件系统中的_any_文件”),FSW越有可能会错过某些内容。 –

回答

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 
} 
+0

感谢您的解决方案,稍作修改。 >>代替目录路径,我写了“D:\”来搜索整个驱动​​器。 >> watcher.IncludeSubdirectories = true;以便wacher搜索子目录。 –

+0

@VK很高兴帮助你。 – Kurubaran

相关问题