FileSystemWatcher 实现文件和文件夹监控
- 关键代码如下
public partial class Form1 : Form
{
private static string filePath="";
private static string directory = "";
private static string watchpath = "";
public Form1()
{
InitializeComponent();
}
#region 文件监控
private FileSystemWatcher _watcher;
public void FileListener(string path)
{
try
{
this._watcher = new FileSystemWatcher();
_watcher.Path = path.Substring(0,path.LastIndexOf("\\"));
_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)
{
WriteLog("Error:" + ex.Message);
}
}
public void fileListenerStart()
{
this._watcher.EnableRaisingEvents = true;
WriteLog("文件监控已经启动...");
}
public void fileListenerStop()
{
this._watcher.EnableRaisingEvents = false;
this._watcher.Dispose();
this._watcher = null;
WriteLog("文件监控已经关闭...");
}
protected void FileWatcher_Created(object sender, FileSystemEventArgs e)
{
WriteLog("新增:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name);
}
protected void FileWatcher_Changed(object sender, FileSystemEventArgs e)
{
WriteLog("变更:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name);
}
protected void FileWatcher_Deleted(object sender, FileSystemEventArgs e)
{
WriteLog("删除:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name);
}
protected void FileWatcher_Renamed(object sender, RenamedEventArgs e)
{
WriteLog($"重命名: OldPath:{e.OldFullPath} \r\n NewPath:{e.FullPath} OldFileName{e.OldName} NewFileName:{e.Name}");
}
#endregion
#region 监控事件
/// <summary>
/// 开始监控
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
if (d.Checked)
{
watchpath = selectDirectory();
directoryListener(watchpath, true);
dirListenerStart();
}
else
{
watchpath = selectFile();
FileListener(watchpath);
fileListenerStart();
}
}
/// <summary>
/// 停止监控
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (d.Checked)
{
dirListenerStop();
}
else
{
fileListenerStop();
}
}
#endregion
#region 选择文件或文件夹
/// <summary>
/// 选择文件
/// </summary>
/// <returns></returns>
private string selectFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "请选择监控文件";
openFileDialog.Filter = "所有文件(*.*)|*.*"; // 设定选择文件
//openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; // 打开app对应的路径
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // 打开桌面
// 如果选定了文件
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// 取得文件路径及文件名
filePath = openFileDialog.FileName;
}
return filePath;
}
/// <summary>
/// 选择文件夹
/// </summary>
/// <returns></returns>
private string selectDirectory()
{
//文件夹浏览
System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
dialog.Description = "请选择监控文件夹";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (string.IsNullOrEmpty(dialog.SelectedPath))
{
MessageBox.Show(this, "文件夹路径不能为空", "提示");
}
}
//选择的文件夹
directory = dialog.SelectedPath;
return directory;
}
#endregion
#region 文件夹监控
private FileSystemWatcher _FileSystemWatcher = new FileSystemWatcher();
/// <summary>
/// 开始监控目录
/// </summary>
/// <param name="path"> 目录路径 </param>
/// <param name="isIncludeSubDir"> 是否包括子目录 </param>
private async void directoryListener(string path, bool isIncludeSubDir = true)
{
_FileSystemWatcher.EnableRaisingEvents = false;
_FileSystemWatcher = new FileSystemWatcher();
_FileSystemWatcher.Path = path;
_FileSystemWatcher.IncludeSubdirectories = isIncludeSubDir;
_FileSystemWatcher.Created += FileSystemWatcher_Created;
_FileSystemWatcher.Renamed += FileSystemWatcher_Renamed;
_FileSystemWatcher.Deleted += FileSystemWatcher_Deleted;
_FileSystemWatcher.Changed += FileSystemWatcher_Changed;
}
public void dirListenerStart()
{
// 开始监控
_FileSystemWatcher.EnableRaisingEvents = true;
//输出到TextArea
WriteLog($"【已开启监控:[{directory}]】");
}
public void dirListenerStop()
{
// 开始监控
_FileSystemWatcher.EnableRaisingEvents = false;
//输出到TextArea
WriteLog($"【已关闭监控:[{directory}]】");
}
private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
WriteLog($"【{GetPathType(e.FullPath)} 更改】{GetPath(e)}");
}
private void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
WriteLog($"【{GetPathType(e.FullPath)} 创建】{GetPath(e)}");
}
private void FileSystemWatcher_Renamed(object sender, FileSystemEventArgs e)
{
WriteLog($"【{GetPathType(e.FullPath)} 重命名】{GetOldPath((RenamedEventArgs)e)} --> {GetPath(e)}");
}
private void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
WriteLog($"【{GetPathType(e.FullPath)} 删除】{GetPath(e)}");
}
private void WriteLog( string info)
{
//托管调用或者跨线程调用
if (InvokeRequired)
{
Action action = () =>
{
rtb_info.AppendText(info);
rtb_info.AppendText("\r\n");
};
Invoke(action);
}
else
{
rtb_info.AppendText(info);
rtb_info.AppendText("\r\n");
}
}
/// <summary>
/// 获取变动的路径的显示字符串
/// </summary>
private string GetPath(FileSystemEventArgs e)
{
return e.FullPath;
// return e.Name;
}
/// <summary>
/// 获取原先路径的显示字符串
/// </summary>
private string GetOldPath(RenamedEventArgs e)
{
return e.OldFullPath;
//return e.OldName;
}
#endregion
#region 判断是文件还是文件夹
/// <summary>
/// 获取路径类型(判断是文件还是文件夹)
/// </summary>
/// <param name="path"> 路径 </param>
/// <returns>PathTypeEnum</returns>
public static PathTypeEnum GetPathType(string path)
{
if (File.Exists(path))
{
return PathTypeEnum.文件;
}
else if (Directory.Exists(path))
{
return PathTypeEnum.文件夹;
}
else
{
return PathTypeEnum.不存在;
}
}
/// <summary>
/// 路径类型枚举
/// </summary>
public enum PathTypeEnum
{
文件,文件夹,不存在
}
#endregion
}
- 项目截图
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16629822.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App