c#如何监视文件或者文件夹的变化

可以使用FileSystemWatcher类来监视文件或者文件夹的变化。

下面的代码可以用来监视重命名的行为。

FileSystemWatcher watcher = new FileSystemWatcher ( ) ;
watcher. Path = @"C:\MyDirectory" ;
watcher. Renamed += new RenamedEventHandler (watcher_Renamed )
watcher. EnableRaisingEvents = true ;

 

void watcher_Renamed ( object sender, RenamedEventArgs e )
{
  Console. WriteLine ( "File Renamed: Old Name: " + e. OldName +
    " New Name: " + e. Name ) ;
}    
 

FileSystemWatcher类的其他事件如下:

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

这些事件都传递一个 FileSystemEventArgs参数,这个参数包含 filename, full path, what action caused the event 等信息.

你可能感兴趣的:(文件夹)