码迷,mamicode.com
首页 > 其他好文 > 详细

监听文件夹

时间:2020-05-28 23:52:16      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:named   eve   rgs   空字符串   code   let   dev   file   sam   

目的

由于一些需求, 需要对关心的文件夹下面的文件做时时的监视包括改名、新增、删除、修改等, 因为文件夹文件数目不少每次重新扫描整个文件将非常的浪费时间.

方案

使用FileSystemWatcher来监听这些感兴趣的变动

示例代码
using System;
using System.IO;

namespace FileSystemWatcherDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            FileSystemWatcher fsw = new FileSystemWatcher();
            fsw.Path = @"./";
            // 不支持使用多个筛选器
            // *.* 所有文件(默认值 空字符串("")还会监视所有文件
            // *.txt 扩展名为 "txt" 的所有文件
            // *recipe.doc 所有以 "食谱" 结尾且扩展名为 "doc" 的文件
            // win*.xml	所有以 "win" 开头且扩展名为 "xml" 的文件
            // ? 任意单字符匹配
            fsw.Filter = "*app*.json";
            fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName |
                               NotifyFilters.DirectoryName;
            fsw.Changed += new FileSystemEventHandler(OnChanged);
            fsw.Created += new FileSystemEventHandler(OnCreated);
            fsw.Deleted += new FileSystemEventHandler(OnDeleted);
            fsw.Renamed += new RenamedEventHandler(OnRenamed);
            fsw.EnableRaisingEvents = true;

            Console.WriteLine("Press ‘q‘ to quit the sample.");
            while (Console.Read() != ‘q‘) ;
        }

        private static void OnRenamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine($"File Name From {e.OldFullPath} To {e.FullPath}.");
        }

        private static void OnDeleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"File {e.FullPath} Removed.");
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"New File {e.FullPath} Created.");
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"File {e.FullPath} Changed.");
        }
    }
}
示例输出
Press ‘q‘ to quit the sample.
File Name From ./New.docx To ./New-app-.json.
File Name From ./新建 Text Document.txt To ./新建 app Text Document.json.
File Name From ./新建 Text Document.txt To ./新建 App 2.json.
File ./New-app-.json Changed.
File ./New-app-.json Changed.
File Name From ./新建 App 2.json To ./App 2.json.
New File ./新建 app Text Document - 副本.json Created.
File ./新建 app Text Document - 副本.json Changed.
New File ./App 2 - 副本.json Created.
File ./App 2 - 副本.json Changed.
File ./App 2 - 副本.json Removed.
File ./App 2.json Removed.
File ./New-app-.json Removed.
File ./新建 app Text Document - 副本.json Removed.
File ./新建 app Text Document.json Removed.

监听文件夹

标签:named   eve   rgs   空字符串   code   let   dev   file   sam   

原文地址:https://www.cnblogs.com/linxmouse/p/12984439.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!