侦听文件系统更改通知,并在目录或目录中的文件发生更改时引发事件。 微软文档:[点击直达](https://learn.microsoft.com/zh-cn/dotnet/api/system.io.filesystemwatcher?view=net-6.0) ## 简单使用 ```csharp private void WatchDir(string path) { var watcher = new FileSystemWatcher(path); watcher.EnableRaisingEvents = true; watcher.IncludeSubdirectories = true; watcher.Created += FileWatcher_Created; } private void FileWatcher_Created(object sender, FileSystemEventArgs e) { if (e.Name.ToLower().EndsWith(".lrc")) return; //因为文件的创建事件触发时,文件可能还未完成创建,比如复制一个文件场景,这个时候文件处于被其他进程占用状态。所以需要等文件完全创建结束之后再操作。 while (true) { FileStream stream = null; try { stream = new FileStream(e.FullPath, FileMode.Open); break; } catch { Task.Delay(1000).Wait(); } finally { stream?.Close(); stream?.Dispose(); } } //todo something } ``` Loading... 侦听文件系统更改通知,并在目录或目录中的文件发生更改时引发事件。 微软文档:[点击直达](https://learn.microsoft.com/zh-cn/dotnet/api/system.io.filesystemwatcher?view=net-6.0) ## 简单使用 ```csharp private void WatchDir(string path) { var watcher = new FileSystemWatcher(path); watcher.EnableRaisingEvents = true; watcher.IncludeSubdirectories = true; watcher.Created += FileWatcher_Created; } private void FileWatcher_Created(object sender, FileSystemEventArgs e) { if (e.Name.ToLower().EndsWith(".lrc")) return; //因为文件的创建事件触发时,文件可能还未完成创建,比如复制一个文件场景,这个时候文件处于被其他进程占用状态。所以需要等文件完全创建结束之后再操作。 while (true) { FileStream stream = null; try { stream = new FileStream(e.FullPath, FileMode.Open); break; } catch { Task.Delay(1000).Wait(); } finally { stream?.Close(); stream?.Dispose(); } } //todo something } ``` 最后修改:2023 年 01 月 12 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏