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

      
    }
  • 项目截图
    image
posted @   码农阿亮  阅读(206)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示