您的位置:首页 > 编程语言 > C#

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、在监控的文件夹目录中增删改文件,就可以看见监控结果。



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: