C#编写程序监测某个文件夹内是否有文件进行了增,删,改的动作?
2017-04-21 10:08
561 查看
新建一个Console应用程序,项目名称为“FileSystemWatcher”,Copy代码进,编译后就可以用了。代码如下: using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Security.Permissions; namespace MyFileSystemWatcher { public class Watcher { public static void Main(string[] args) { Run(); } [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public static void Run() { string[] args = System.Environment.GetCommandLineArgs(); if (args.Length != 2) { Console.WriteLine("使用方式: FileSystemWatcher.exe DirectoryPath"); return; } FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = args[1]; /* 设置为监视 LastWrite 和 LastAccess 时间方面的更改,以及目录中文本文件的创建、删除或重命名。 */ watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // 只监控.txt文件 watcher.Filter = "*.txt"; // 添加事件处理器。 watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new FileSystemEventHandler(OnChanged); watcher.Renamed += new RenamedEventHandler(OnRenamed); // 开始监控。 watcher.EnableRaisingEvents = true; // 输入q推出程序。 Console.WriteLine("按 \'q\' 推出程序。"); while (Console.Read() != 'q') ; } // 定义事件处理器。 private static void OnChanged(object source, FileSystemEventArgs e) { //如果更改、创建或删除文件,文件路径将被输出到控制台。 Console.WriteLine("文件: " + e.FullPath + " " + e.ChangeType); } private static void OnRenamed(object source, RenamedEventArgs e) { // 在文件重命名后,旧路径和新路径都输出到控制台。 Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath); } } } 使用说明(具体看图): 1、打开cmd窗口,先定位到FileSystemWatcher.exe所在的文件夹目录; 2、输入【FileSystemWatcher.exe 文件夹目录名称】,回车; 3、在监控的文件夹目录中增删改文件,就可以看见监控结果。
相关文章推荐
- C#编写程序监测某个文件夹内是否有文件进行了增,删,改的动作
- C#编写程序监测某个文件夹内是否有文件进行了增,删,改的动作
- 如何用C#编写程序监测某个文件夹内是否有文件进行了增,删,改的动作?
- 编写高质量代码改善C#程序的157个建议——建议115:通过HASH来验证文件是否被篡改
- C#判断文件及文件夹是否存在并创建(C#判断文件夹存在)
- vc编写文件夹与文件打包程序
- C#中判断文件或文件夹是否存在
- 面试题,编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。
- C# 判断文件和文件夹是否存在并创建
- C# 判断文件和文件夹是否存在
- C# 检查文件夹和文件是否存在
- C#判断文件是否存在和文件夹是否存在(Windows Mobile上可以使用)
- 用C#监视多个文件夹,然后调用flvmdi对这个flv文件进行信息注入.
- C#判断文件及文件夹是否存在并创建
- C#中判断文件或文件夹是否存在
- C# 检查文件夹和文件是否存在
- ASP.net 2.0 C#判断文件夹与文件是否存在
- C#判断文件及文件夹是否存在
- ASP.net 2.0 C#判断文件夹与文件是否存在
- C#怎样判断文件是否存在和文件夹是否存在