.net 监听本地目录


捕获事件FileSystemWatcher

例子:

/// 
        /// 监听目录
        /// 
        /// 目录
        /// 过滤器(文件类型)
        /// 是否递归子目录
        static void Watch(string path, string filter, bool includeSubDirs)
        {
            using (var watcher=new FileSystemWatcher(path,filter))
            {
                watcher.Created += Watcher_Changed;
                watcher.Deleted += Watcher_Changed;
                watcher.Changed += Watcher_Changed;
                watcher.Renamed += Watcher_Renamed;  
                 
                watcher.Error += Watcher_Error;
                watcher.IncludeSubdirectories = includeSubDirs;
                watcher.EnableRaisingEvents = true;

                Console.WriteLine("Listening for - pree to end");
                Console.ReadLine();
            }
           
        }

        private static void Watcher_Renamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine($"Renamed:{e.OldFullPath} => {e.FullPath}");
        }

        private static void Watcher_Error(object sender, ErrorEventArgs e)
        {
            Console.WriteLine($"Error:+{e.GetException().Message}");
        }

        private static void Watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"File {e.FullPath} has been {e.ChangeType}");
        }

static void Main(string[] args)
        {

            Watch(@"C:\Users\Administrator\Desktop\IO", "*.*", true);
}