带有控制台应用程序的 FileSystemWatcher

FileSystemWatcher with the console application

为了在我的 Web 应用程序中发送批量电子邮件,我使用 filewatcher 来发送应用程序。

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

我已经把可执行文件的快捷方式复制到以下路径

%appdata%\Microsoft\Windows\StartMenu\Programs

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

在 运行 可执行文件之后,文件监视程序并不总是监视。 在搜索了一些网站后,我发现我们需要添加代码

new System.Threading.AutoResetEvent(false).WaitOne();

这样添加可执行文件并查看文件夹的方法对吗?

在 运行 控制台应用程序(没有上面的代码)之后文件不会一直被监视吗?

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

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);

因为它是一个 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();
}

您的代码仅跟踪 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();
}

您还必须注意缓冲区溢出。 FROM MSDN FileSystemWatcher

The Windows operating system notifies your component of file changes in a buffer created by the FileSystemWatcher. If there are many changes in a short time, the buffer can overflow. This causes the component to losing track of changes in the directory, and it will only provide the blanket notification. Increasing the size of the buffer with the InternalBufferSize property is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small yet large enough to not miss any file change events. To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties so you can filter out unwanted change notifications.