C#监控文件夹变化的方法
程序员文章站
2023-12-16 12:09:10
本文实例讲述了c#监控文件夹变化的方法。分享给大家供大家参考。具体实现方法如下:
当需要监控某一文件,filesystemwatcher类提供了created, dele...
本文实例讲述了c#监控文件夹变化的方法。分享给大家供大家参考。具体实现方法如下:
当需要监控某一文件,filesystemwatcher类提供了created, deleted,rename等事件。
就拿filesystemwatcher的created事件来说,该事件类型是filesystemeventhandler。
复制代码 代码如下:
public delgate void filesystemeventhandler(object sender, filesystemeventargs e)
其中参数:
sender表示事件的发起者
e表示事件参数
在c盘创建temp文件夹。
客户端。
复制代码 代码如下:
class program
{
static void main(string[] args)
{
var watcher = new filesystemwatcher(@"c:\temp");
watcher.enableraisingevents = true; //启用filesystemwatcher
watcher.created += new filesystemeventhandler(oncreated);
watcher.deleted += new filesystemeventhandler(ondeleted);
watcher.renamed += new renamedeventhandler(onrenamed);
console.readkey();
}
static void ondeleted(object sender, filesystemeventargs e)
{
console.writeline("{0}:{1}", e.changetype, e.name);
}
static void oncreated(object sender, filesystemeventargs e)
{
console.writeline("{0}:{1}", e.changetype, e.name);
}
static void onrenamed(object sender, renamedeventargs e)
{
console.writeline("{0}:原文件名{1},新文件名{2}", e.changetype, e.oldname, e.name);
}
}
{
static void main(string[] args)
{
var watcher = new filesystemwatcher(@"c:\temp");
watcher.enableraisingevents = true; //启用filesystemwatcher
watcher.created += new filesystemeventhandler(oncreated);
watcher.deleted += new filesystemeventhandler(ondeleted);
watcher.renamed += new renamedeventhandler(onrenamed);
console.readkey();
}
static void ondeleted(object sender, filesystemeventargs e)
{
console.writeline("{0}:{1}", e.changetype, e.name);
}
static void oncreated(object sender, filesystemeventargs e)
{
console.writeline("{0}:{1}", e.changetype, e.name);
}
static void onrenamed(object sender, renamedeventargs e)
{
console.writeline("{0}:原文件名{1},新文件名{2}", e.changetype, e.oldname, e.name);
}
}
当然,可以通过 watcher.renamed += oncreated;注册事件。
希望本文所述对大家的c#程序设计有所帮助。