带控制台应用程序的FileSystemWatcher

Jee*_*Jsb 5 c# file-watcher

要在我的Web应用程序中发送批量电子邮件,我使用filewatcher发送应用程序.

我计划用控制台应用程序而不是Windows服务或调度程序来编写filewatcher.

我已在以下路径中复制了可执行文件快捷方式.

%appdata%\ Microsoft\Windows\Start Menu\Programs

参考:https://superuser.com/questions/948088/how-to-add-exe-to-start-menu-in-windows-10

运行可执行文件后,不会始终监视文件观察程序.搜索了一些网站后,我发现我们需要添加代码

new System.Threading.AutoResetEvent(false).WaitOne();
Run Code Online (Sandbox Code Playgroud)

这是添加可执行文件和观看文件夹的正确方法吗?

运行控制台应用程序(没有上面的代码)后,文件将不会被始终监视?

什么是使用文件观察者的正确方法?

FileSystemWatcher watcher = new FileSystemWatcher();
string filePath = ConfigurationManager.AppSettings["documentPath"];
watcher.Path = filePath;
watcher.EnableRaisingEvents = true;
watcher.NotifyFilter = NotifyFilters.FileName; 
watcher.Filter = "*.*";
watcher.Created += new FileSystemEventHandler(OnChanged);
Run Code Online (Sandbox Code Playgroud)

Ali*_*ami 11

因为它是一个Console Application你需要在Main方法中编写代码来等待而不是在运行代码后立即关闭.

static void Main()
{
   FileSystemWatcher watcher = new FileSystemWatcher();
   string filePath = ConfigurationManager.AppSettings["documentPath"];
   watcher.Path = filePath;
   watcher.EnableRaisingEvents = true;
   watcher.NotifyFilter = NotifyFilters.FileName;
   watcher.Filter = "*.*";
   watcher.Created += new FileSystemEventHandler(OnChanged);


   // wait - not to end
   new System.Threading.AutoResetEvent(false).WaitOne();
}
Run Code Online (Sandbox Code Playgroud)

如果要查看需要为观察程序对象设置的子root文件夹,代码仅跟踪文件夹中的更改IncludeSubdirectories=true.

static void Main(string[] args)
{
   FileSystemWatcher watcher = new FileSystemWatcher();
   string filePath = @"d:\watchDir";
   watcher.Path = filePath;
   watcher.EnableRaisingEvents = true;
   watcher.NotifyFilter = NotifyFilters.FileName;
   watcher.Filter = "*.*";

   // will track changes in sub-folders as well
   watcher.IncludeSubdirectories = true;

   watcher.Created += new FileSystemEventHandler(OnChanged);

   new System.Threading.AutoResetEvent(false).WaitOne();
}
Run Code Online (Sandbox Code Playgroud)

您还必须注意缓冲区溢出.来自MSDN FileSystemWatcher

Windows操作系统会在FileSystemWatcher创建的缓冲区中通知组件文件更改.如果 在短时间内有许多变化,缓冲区可能会溢出.这会导致组件无法跟踪目录中的更改,并且只会提供一揽子通知.使用InternalBufferSize属性增加缓冲区的大小是昂贵的,因为它来自无法换出到磁盘的非分页内存,因此请保持缓冲区尽小但足够大,以免错过任何文件更改事件.要避免缓冲区溢出,请使用NotifyFilter和IncludeSubdirectories属性,以便过滤掉不需要的更改通知.