You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FileSystemWatcher调用FileInfo.Create()时不触发Created事件的解决方法

解决FileSystemWatcher不触发Created事件的问题

我刚测试了你的代码,发现问题出在NotifyFilter的设置上——你当前的配置没有包含NotifyFilters.FileName,而Created事件需要监控目录中文件名的新增变化才能触发。

当你右键创建文件时,系统会触发一系列完整的文件系统操作(包括文件名的注册),但如果FileName不在监控范围内,FileSystemWatcher就无法捕获到文件创建的通知。

修改后的代码

using System;
using System.IO;
using System.Security.Permissions;

namespace MCVEConsole
{
    class Program
    {
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        static void Main(string[] args)
        {
            DirectoryInfo myDirectory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))
                .CreateSubdirectory("MCVEConsole");

            FileSystemWatcher fSW = new FileSystemWatcher(myDirectory.FullName, "*.txt")
            {
                // 添加FileName和DirectoryName到监控筛选器,这是捕获创建/删除事件的关键
                NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | 
                               NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.LastWrite
            };

            fSW.Created += _Changed;
            fSW.Deleted += _Changed;
            fSW.EnableRaisingEvents = true;

            // 创建文件的逻辑保持不变
            new FileInfo(Path.Combine(myDirectory.FullName, "foo.txt")).Create().Close();

            void _Changed(object sender, FileSystemEventArgs e) => Console.WriteLine($"事件触发:{e.ChangeType} - {e.Name}");

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}

额外优化建议

如果修改后仍偶尔出现不触发的情况(比如极端快速的批量文件操作),可以尝试:

  • 增大FileSystemWatcher的BufferSize(默认8192字节),避免因通知消息过多导致缓冲区溢出;
  • 在文件创建后添加极短延迟(如System.Threading.Thread.Sleep(50)),给文件系统足够时间发送通知;
  • 确保EnableRaisingEvents在绑定事件之后再设为true(你的代码已经符合这个要求)。

内容的提问来源于stack exchange,提问作者Will

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:03:41