using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace HelloCsharp
{
class Program
{
static void Main(string[] args)
{
FileListenerServer f1 = new FileListenerServer(@"c:\");
f1.Start();
Console.ReadKey();
}
}
public class FileListenerServer
{
private FileSystemWatcher _watcher;
public FileListenerServer()
{
}
public FileListenerServer(string path)
{
try
{
this._watcher = new FileSystemWatcher();
_watcher.Path = path;
_watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.DirectoryName;
_watcher.IncludeSubdirectories = true;
_watcher.Created += new FileSystemEventHandler(FileWatcher_Created);
_watcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);
_watcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted);
_watcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed);
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}
}
public void Start()
{
this._watcher.EnableRaisingEvents = true;
Console.WriteLine("文件监控已经启动...");
}
public void Stop()
{
this._watcher.EnableRaisingEvents = false;
this._watcher.Dispose();
this._watcher = null;
}
protected void FileWatcher_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("新增:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name);
}
protected void FileWatcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("变更:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name);
}
protected void FileWatcher_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("删除:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name);
}
protected void FileWatcher_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine("重命名: OldPath:{0} NewPath:{1} OldFileName{2} NewFileName:{3}", e.OldFullPath, e.FullPath, e.OldName, e.Name);
}
}
}
C#监控某个文件夹中文件和文件夹变化
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
上一篇:C#网络操作相关的类
下一篇:深入了解JVM虚拟机总结
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
C#~使用FileSystemWatcher来监视文件系统的变化
对于一个文件夹的改变,
支付宝 扫一扫 c# -
C# 获取目录下文件
C# 获取目录下文件
字段 子目录 添加行 文件路径 i++