C# 監(jiān)聽文件和目錄系統(tǒng)變化(FileSystemWatcher)
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
一、常用事件二、基本屬性
三、代碼示例 private static void FileWatcher(string path, string filter)
{
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
fileSystemWatcher.Path = path;
fileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
|NotifyFilters.DirectoryName;
//文件類型,支持通配符,“*.txt”只監(jiān)視文本文件
fileSystemWatcher.Filter = filter; // 監(jiān)控的文件格式
watch.IncludeSubdirectories = true; // 監(jiān)控子目錄
fileSystemWatcher.Changed += new FileSystemEventHandler(OnProcess);
fileSystemWatcher.Created += new FileSystemEventHandler(OnProcess);
fileSystemWatcher.Renamed += new RenamedEventHandler(OnRenamed);
fileSystemWatcher.Deleted += new FileSystemEventHandler(OnProcess);
//表示當(dāng)前的路徑正式開始被監(jiān)控,一旦監(jiān)控的路徑出現(xiàn)變更,F(xiàn)ileSystemWatcher 中的指定事件將會(huì)被觸發(fā)。
fileSystemWatcher.EnableRaisingEvents = true;
}
private static void OnProcess(object source, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
OnCreated(source, e);
}
else if (e.ChangeType == WatcherChangeTypes.Changed)
{
OnChanged(source, e);
}
else if (e.ChangeType == WatcherChangeTypes.Deleted)
{
OnDeleted(source, e);
}
}
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File created: {0} {1} {2}", e.ChangeType, e.FullPath, e.Name);
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File changed: {0} {1} {2}", e.ChangeType, e.FullPath, e.Name);
}
private static void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("File deleted: {0} {1} {2}", e.ChangeType, e.FullPath, e.Name);
}
private static void OnRenamed(object source, FileSystemEventArgs e)
{
Console.WriteLine("File renamed: {0} {1} {2}", e.ChangeType, e.FullPath, e.Name);
} 總結(jié)該文章在 2023/12/26 22:00:53 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |