You can register to be informed of any changes in the windows file system. You can filter based on a filename, or type of event such as delete create, modify.
C# Code
Add the following include:
using System.IO;
Create a windows application and in a form place this code in the Form Load event:
FileSystemWatcher fsw = new FileSystemWatcher();
fsw.Path = "c://";
fsw.Filter = "*.*";
fsw.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.FileName |
NotifyFilters.DirectoryName;
//Setup Events
fsw.Changed += new FileSystemEventHandler(FileChanged);
fsw.Created += new FileSystemEventHandler(FileCreated);
fsw.Deleted += new FileSystemEventHandler(FileDeleted);
fsw.Renamed += new RenamedEventHandler(FileRenamed);
//Start
fsw.EnableRaisingEvents = true;
Add these methods to the forms as well:
public static void FileChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File {0} was Changed.",e.FullPath);
}
public static void FileCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File {0} was Created.",e.FullPath);
}
public static void FileDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("File {0} was Deleted.",e.FullPath);
}
public static void FileRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("File {0} was renamed to {1}", e.OldFullPath, e.FullPath);
}
Running the Example
Run your application and ensure you can see the Ouput window to view the console.write messages. Then create a new file in c:/, you will notice a message get sent to the console. Then delete the file and you will get another message. C# makes it easy to capture events from the OS like this, perfect for monitoring
本文介绍如何使用C#的FileSystemWatcher类来监控Windows文件系统的更改。通过简单的代码示例,展示了如何监听文件创建、删除、修改及重命名等事件。
483

被折叠的 条评论
为什么被折叠?



