System.IO.FileSystemWatcher 监视目录文件的状态

本文介绍了如何使用System.IO.FileSystemWatcher类来监视目录文件的状态,包括文件的创建、删除和更改事件。通过设置Filter可以指定监控特定类型的文件,而NotifyFilter则用于选择要监视的文件属性变化。需要注意的是,启用EnableRaisingEvents属性才能使事件生效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

System.IO.FileSystemWatcher

MSDN 说明:侦听文件系统更改通知,并在目录或目录中的文件发生更改时引发事件。 

这两天看到论坛上关于如何监视目录文件的状态帖子很多,自己今天也在看System.IO下面的类,就顺便把他给看了,并实验了一下,其实此类用起来非常简单,不过有两三个地方需要注意下,下面把需要注意的地方说一下

  System.IO.FileSystemWatcher watch = new FileSystemWatcher("D://1//");       //初始化目录监视
            watch.Filter = "*.txt";                      //监视的对象,目录中监视哪些文件,默认为*.*
           //不过这里有个好玩的地方,实验证明,通配符可以用在很多地方,比如可以设置成为  watch.Filter = "*.tx*";    针对具体文件就写具体文件名
            watch.Changed += new FileSystemEventHandler(watch_Changed);         //文件改变事件
           

public class CustomerWatcher { System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher(); List<string> currentpathList= new List<string>(); public void Watch(string Path) { watcher.Path = Path; watcher.NotifyFilter = System.IO.NotifyFilters.LastAccess | System.IO.NotifyFilters.LastWrite | System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.DirectoryName; watcher.Changed += new System.IO.FileSystemEventHandler(OnChanged); watcher.Created += new System.IO.FileSystemEventHandler(OnCreated); watcher.Deleted += new System.IO.FileSystemEventHandler(OnChanged); watcher.Renamed += new System.IO.RenamedEventHandler(OnRenamed); watcher.EnableRaisingEvents = true; } private void OnChanged(object source, System.IO.FileSystemEventArgs e) { Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); string filePath = e.FullPath; List<string> filePathList = filePath.Split("\\").ToList(); int filePathListCount = filePathList.Count(); if (filePathListCount < 6) { return; } else if (filePathListCount > 6) { for(int i= filePathListCount - 1;i>=6;i--) { filePathList.RemoveAt(i); } } string productRootPath = string.Join("\\", filePathList); if(currentpathList.Contains(productRootPath)) { return; } int delayTime = 300; Thread.Sleep(delayTime); string cust_code=filePathList[2]; string cusr_code_short = cust_code.Split('(')[0]; if(cusr_code_short=="AZ") { } currentpathList.Add(productRootPath); }修改代码,中间这部分代码放到新的线程里面运行,不要阻塞主线程
最新发布
03-20
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值