现有一个需求如下:监控某个目录中的文件修改,创建,删除等信息,并记录下来.

这里用到FileSystemWatcher类.由于考虑到文件的写入量会很频率,所以考虑先将监听到的消息记录到内存中。

监听部分的代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FileEventListener
{
    public partial class FSWControl : Form
    {
        static int count = 0;
        static FileSystemWatcher watcher = new FileSystemWatcher();
        static int eventCount = 0;

        //static List<string> files = new List<string>();
        public FSWControl()
        {
            InitializeComponent();
            WatcherStrat(@"D:\test\", "*.tr", true, true);
        }

        /// <summary>
        /// 初始化监听
        /// </summary>
        /// <param name="StrWarcherPath">需要监听的目录</param>
        /// <param name="FilterType">需要监听的文件类型(筛选器字符串)</param>
        /// <param name="IsEnableRaising">是否启用监听</param>
        /// <param name="IsInclude">是否监听子目录</param>
        private static void WatcherStrat(string StrWarcherPath, string FilterType, bool IsEnableRaising, bool IsInclude)
        {
            //初始化监听
            watcher.BeginInit();
            //设置监听文件类型
            watcher.Filter = FilterType;
            //设置是否监听子目录
            watcher.IncludeSubdirectories = IsInclude;
            //设置是否启用监听?
            watcher.EnableRaisingEvents = IsEnableRaising;
            //设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)
            watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
            //设置监听的路径
            watcher.Path = StrWarcherPath;
            //注册创建文件或目录时的监听事件
            //watcher.Created += new FileSystemEventHandler(watch_created);
            //注册当指定目录的文件或者目录发生改变的时候的监听事件
            watcher.Changed += new FileSystemEventHandler(watch_changed);
            //注册当删除目录的文件或者目录的时候的监听事件
            watcher.Deleted += new FileSystemEventHandler(watch_deleted);
            //当指定目录的文件或者目录发生重命名的时候的监听事件
            watcher.Renamed += new RenamedEventHandler(watch_renamed);
            //结束初始化
            watcher.EndInit();
        }

        /// <summary>
        /// 创建文件或者目录时的监听事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void watch_created(object sender, FileSystemEventArgs e)
        {
            //事件内容
            output("create:" + e.FullPath);
        }

        /// <summary>
        /// 当指定目录的文件或者目录发生改变的时候的监听事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void watch_changed(object sender, FileSystemEventArgs e)
        {
            //事件内容
            //事件内容
            output("change:" + e.FullPath);
        }
        /// <summary>
        /// 当删除目录的文件或者目录的时候的监听事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void watch_deleted(object sender, FileSystemEventArgs e)
        {
            //事件内容
            output("del:" + e.FullPath);
        }
        /// <summary>
        /// 当指定目录的文件或者目录发生重命名的时候的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void watch_renamed(object sender, RenamedEventArgs e)
        {
            //事件内容
            output("rename:" + e.FullPath);
        }
        /// <summary>
        /// 启动或者停止监听
        /// </summary>
        /// <param name="IsEnableRaising">True:启用监听,False:关闭监听</param>
        private void WatchStartOrSopt(bool IsEnableRaising)
        {
            watcher.EnableRaisingEvents = IsEnableRaising;
        }

        private static void output(string text)
        {
            //FileStream fs = new FileStream("D:\\listen.txt", FileMode.Append);
            //StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            //sw.WriteLine(text);
            //sw.Close();
            //fs.Close();
            //files.Add(text);
            eventCount++;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string name = count.ToString() + "_" + eventCount.ToString();
            FileStream fs = new FileStream("D:\\listen_" + name + ".txt", FileMode.Append);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            //foreach (string text in files)
            //{
            //    sw.WriteLine(text);
            //}
            sw.WriteLine("共收到事件:" + eventCount.ToString());
            //files.Clear();
            eventCount = 0;
            sw.Close();
            fs.Close();
            count++;
            MessageBox.Show("打印完成:" + name, "提示", MessageBoxButtons.OK);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            WatchStartOrSopt(false);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            WatchStartOrSopt(true);
        }
    }
}

然后写一个生成文件的程序用于测试,由于可能需要多个写入一起跑,采用传入参数的方式进行调用程序。共三个参数:第一个为标识,第二个为生成文件的数量,第三个为开始运行的时间:

如 FileCreater.exe 1 1000 121000 则表示这个实例的名称为1,连续生成1000个文件,在12:10:00开始执行。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FileCreater
{
    public partial class Form1 : Form
    {
        string filePre = "";
        string startTime = "";

        public Form1(string[] args)
        {
            filePre = args[0];
            startTime = args[2];
            InitializeComponent();

            timer1.Interval = 100;
            timer1.Tick += button1_Click;
            timer1.Enabled = true;
            this.Text = "FileCreater" + filePre + "_" + startTime;
            this.numericUpDown1.Value = int.Parse(args[1]);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label3.Text = DateTime.Now.ToString("HHmmss") + "|" + startTime;
            if (int.Parse(DateTime.Now.ToString("HHmmss")) > int.Parse(startTime))
            {
                label3.Text = numericUpDown1.Value.ToString();
                for (int i = 1; i <= numericUpDown1.Value; i++)
                {
                    //string time = DateTime.Now.ToString("ddhhMMss");
                    string file = string.Format(@"{0}\{1}_{2}.tr", textBox1.Text, i, filePre);
                    FileStream fs = new FileStream(file, FileMode.Append);
                    StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                    sw.WriteLine(i.ToString());
                    sw.Close();
                    fs.Close();
                }
                timer1.Stop();
            }
            //MessageBox.Show("已完成", "提示", MessageBoxButtons.OK);

            Application.Exit();
        }
    }
}

测试过程中发现如下现象:

1.一个生成文件程序,连续生成10W的文件时会发生计数器记录下的值小于或多于10W

FileSystemWatcher监听文件事件的更多相关文章

  1. C# FileSystemWatcher监听文件事件

    现有一个需求如下:监控某个目录中的文件修改,创建,删除等信息,并记录下来. 这里用到FileSystemWatcher类.由于考虑到文件的写入量会很频率,所以考虑先将监听到的消息记录到内存中. 监听部 ...

  2. 关于FileSystemWatcher监听文件创建

    FileSystemWatcher中的Created事件不但可以监听用户创建的文件,当用户删除某个文件时,系统会在再监听的那个盘上的回收站创建一个文件,在回收站创建的文件也会触发Created事件,而 ...

  3. 文件和文件夹不存在的时候,FileSystemWatcher 监听不到文件的改变?如果递归地监听就可以了

    当你需要监视文件或文件夹的改变的时候,使用 FileSystemWatcher 便可以完成.不过,FileSystemWatcher 对文件夹的监视要求文件夹必须存在,否则会产生错误“无效路径”. 那 ...

  4. FileSystemWatcher监听文件是否有被修改

    作用:监听文件系统更改通知,并在目录或目录中的文件更改时引发事件. 需求:监听特定文件是否修改,然后做出相应的操作. 方法: ①利用一个线程,一直去查找该指定的文件是否有被修改,如果修改则操作特定步骤 ...

  5. 使用FileSystemWatcher监听文件状态

    更新记录 本文迁移自Panda666原博客,原发布时间:2021年7月2日. 一.FileSystemWatcher类型介绍 在.NET中使用 FileSystemWatcher 类型可以进行监视指定 ...

  6. linux实时文件事件监听--inotify

    一.inotify简介 inotify是Linux内核2.6.13 (June 18, 2005)版本新增的一个子系统(API),它提供了一种监控文件系统(基于inode的)事件的机制,可以监控文件系 ...

  7. c# 监听文件夹动作

    static FileSystemWatcher watcher = new FileSystemWatcher(); /// <summary>        /// 初始化监听     ...

  8. C#监听文件

    //全局变量 public static FileSystemWatcher Watcher; /// <summary>        /// 设置监听配置        /// < ...

  9. Delphi目录监控、目录监听

    资料地址: 1.https://www.cnblogs.com/studypanp/p/4890970.html 单元代码: (************************************ ...

随机推荐

  1. dedecms织梦网站本地迁移到服务器后,后台更新栏目文档提示模板文件不存在,无法解析文档!的解决办法

    解决办法: 1.系统设置-系统基本参数-站点设置-网页主页链接,替换为空 2.系统设置-系统基本参数-核心设置-DedeCMS安装目录,替换为空

  2. python 继承:重写、拓展(六)

    1.继承:父类有的子类也有 2.多继承:若继承多个父类有相同的函数,则继承前面的函数,传递参数的个数也与继承的函数位置有关 3.超继承:针对继承一个父类使用,不仅有父类的特写同时也有自己的新特性  s ...

  3. C++ Primer 第 5 版 习题参考答案

    从 5 月初 - 8 月 16 日,每天基本都在啃 C++ 的语法.起初直接看C++ Primer 中文版(第 5 版),发现后边的章节看着很吃力.所以就转而看了清华大学郑莉老师和李超老师的视频C++ ...

  4. k8sDaemonSet控制器

    DaemonSet用于再集群中的全部节点上同时运行一份指定的pod资源副本,后续新加入的工作节点也会自动创建一个相关的pod对象,当从集群中移除节点时,此类pod对象也将被自动回收而无须重建.也可以使 ...

  5. winform的Textbox设置只读之后使用ForeColor更改颜色

    winform的Textbox设置只读之后设置ForeColor更改颜色无效.这是 TextBox 默认的行为. 解决方法:设置为只读之后,修改控件的BackColor,再设置ForeColor就可以 ...

  6. 2019春Python程序设计练习6(0423--0429)

    1-1 定义Python函数时,如果函数中没有return语句,则默认返回空值None. (2分) T         F 1-2 在函数内部没有任何声明的情况下直接为某个变量赋值,这个变量一定是函数 ...

  7. 2019春Python程序设计练习5(0416--0422)

    6-1 6-1.使用函数求特殊a串数列和 (30 分)   给定两个均不超过9的正整数a和n,要求编写函数fn(a,n) 求a+aa+aaa++⋯+aa⋯aa(n个a)之和,fn须返回的是数列和 函数 ...

  8. 【HDOJ5447】Good Numbers(数论)

    题意: 思路:From https://blog.csdn.net/qq_36553623/article/details/76683438 大概就是把1e6里面的质因子能除的都除光之后借助两者gcd ...

  9. 半径R覆盖最多点

    struct point { double x, y; }; point p[N]; struct alpha { double v; bool flag; bool friend operator ...

  10. ThreadPool用法与优势

    1.  线程池的优点: 合理利用线程池能够带来三个好处.第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗.第二:提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执 ...