关于我的FileSystemWatcher(文件监控)

本文详细介绍如何使用FileSystemWatcher组件监控文件系统的变化,包括文件创建、删除、更改和重命名事件的处理。通过设置NotifyFilter和EnableRaisingEvents属性,有效避免事件重复触发,确保程序稳定运行。

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

首先 ,创建全局变量的FileSystemWatcher

  private FileSystemWatcher watch = new FileSystemWatcher(); 
  watch.Path = Path;//设定路径
  watch.Filter = "*.*";
  watch.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.LastAccess;

   watch.Renamed += new RenamedEventHandler(watcher_Renamed);
   watch.Deleted += new FileSystemEventHandler(DeleteWatch);
   watch.Created += new FileSystemEventHandler(CreateWatch);
   watch.Changed += new FileSystemEventHandler(ChangeWatch); 
   watch.EnableRaisingEvents = true;

应用方式:

int ChangeCount = 0;//设定第二次触发时进行数据处理
    public void ChangeWatch(object sender, FileSystemEventArgs e)
    {
        Thread.Sleep(200);
        watch.EnableRaisingEvents = false;
        if (ChangeCount > 0)
        {
            if (e.FullPath.Contains("JPG") || e.FullPath.Contains("jpg"))
            {
                FileInfo OneFile = new FileInfo(e.FullPath);
                if (PhotoFiles.Where(x => e.FullPath.Contains(x.Name)).Count() < 1)
                {
                    GetNewFileDo(OneFile);
                }

            }
            ChangeCount = 0;
        }
        else
        {
            ChangeCount++;
        }
      
        watch.EnableRaisingEvents = true;
    }

避免触发两遍的问题?
首先设置NotifyFilter为LastWrite,这个就屏蔽了因为杀毒软件等各种外部因素导致Changed事件被触发。
然后设置它的EnableRaisingEvents属性如下:

private void fsw_Changed(object sender,EventArgs e)
{
    fsw.EnableRaisingEvents = false;
    LoadTreeViewData();
    fsw.EnableRaisingEvents = true;
}

这样,先设置为false然后处理完文件之后再设置为true即可。
其中

static void watcher_Renamed(object sender, RenamedEventArgs e)
{
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.Write(e.ChangeType);
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(" ");
            Console.Write(e.OldName);
            Console.Write(e.OldFullPath);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write(" ");
            Console.Write(e.Name);
            Console.Write(e.FullPath);
            Console.Write(Thread.CurrentThread.Name);
            Console.Write("\r\n");
}
 

关于文件的判定操作:

        #region [ 检测文件是否占用 ]
        /// <summary>
        /// 检测文件是否占用
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        static bool IsFileReady(string filename)
        {
            var fi = new FileInfo(filename);
            FileStream fs = null;
            try
            {
                fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.None);
                return true;
            }
            catch (IOException)
            {
                return false;
            }

            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }
        #endregion

另一个比较全面的操作方法:

  private static volatile object _lock = true;
        static void onFileSystem_Changed(object sender, FileSystemEventArgs e)
        {
            lock (_lock)
            {
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("[");
                Console.Write(DateTime.Now.ToString("HH:mm:ss"));
                Console.Write("] ");

                switch (e.ChangeType.ToString().ToLower())
                {
                    case "created":
                        //while (!IsFileReady(e.FullPath))
                        //{
                        //    if (!File.Exists(e.FullPath))
                        //        return;
                        //    Thread.Sleep(100);
                        //}
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(e.ChangeType);
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.Write(" ");
                        Console.Write(e.Name);
                        Console.Write(" ");
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                        Console.Write(e.FullPath);

                        break;
                    case "deleted":
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write(e.ChangeType);
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.Write(" ");
                        Console.Write(e.Name);
                        Console.Write(" ");
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                        Console.Write(e.FullPath);
                        break;
                    case "changed":
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.Write(e.ChangeType);
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.Write(" ");
                        Console.Write(e.Name);
                        Console.Write(" ");
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                        Console.Write(e.FullPath);
                        break;
                }

                Console.Write("\r\n");
            }
        }
        static void watcher_Renamed(object sender, RenamedEventArgs e)
        {
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.Write(e.ChangeType);
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(" ");
            Console.Write(e.OldName);
            Console.Write(e.OldFullPath);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write(" ");
            Console.Write(e.Name);
            Console.Write(e.FullPath);
            Console.Write(Thread.CurrentThread.Name);
            Console.Write("\r\n");
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值