C++ Programmer's Cookbook

{C++ 基础} {C++ 高级} {C#界面,C++核心算法} {设计模式} {C#基础}

Handle FileSystem Notifications with the FileSystemWatcher

Author: James Foster Date Posted: 12/15/2001 .NET Version: 1.0.3705
The FileSystemWatcher is a file system notification class. With this class, you can monitor a specific directory or file for changes, and be notified when the event occurs. In this article, we'll create a simple windows application that prints a message when text files in a specific path are accessed. The concepts presented here can be used for more complicated apps, such as a security monitoring tool for website changes, or perhaps an error handling procedure when an error log is written to the filesystem.

Setting up the FileSystemWatcher is simple. Typically, you will follow these steps:

  1. Instantiate the FileSystemWatcher
  2. Set the Path to monitor
  3. Set any Filters
  4. Set your event handler
The following code snippet shows the core of our sample application. As you can see, we first instantiate the FileSystemWatcher class in the System.IO namespace. Next we set the path to monitor, as well as the filters. Here, we are interested in text files being modified on the f: drive. We've defined an OnChanged method, and set this method as the EventHandler.

public Form1()
{
    //Required for Windows Form Designer support
    InitializeComponent();
    
    //Set up File Watcher
    System.IO.FileSystemWatcher watcher=new System.IO.FileSystemWatcher();
    watcher.Path = "f:\\";
    watcher.Filter ="*.txt";
    watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
    watcher.EnableRaisingEvents =true;
    watcher.Changed +=new System.IO.FileSystemEventHandler(OnChanged);
}
    
privatevoid OnChanged(objectsender, System.IO.FileSystemEventArgs e)
{
    textBox1.Text += e.Name.ToString()+" changed at "+ System.DateTime.Now.ToString();
}
C#VB

When an event is fired, we use the FileSystemEventArgs to get the name of the file triggering the event, and display a message to the screen noting the time we learned of the event. The screenshot below shows our application in action:

posted on 2006-04-14 12:45 梦在天涯 阅读(1258) 评论(0)  编辑 收藏 引用 所属分类: C#/.NET


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


公告

EMail:itech001#126.com

导航

统计

  • 随笔 - 461
  • 文章 - 4
  • 评论 - 746
  • 引用 - 0

常用链接

随笔分类

随笔档案

收藏夹

Blogs

c#(csharp)

C++(cpp)

Enlish

Forums(bbs)

My self

Often go

Useful Webs

Xml/Uml/html

搜索

  •  

积分与排名

  • 积分 - 1797143
  • 排名 - 5

最新评论

阅读排行榜