【问题标题】:FileSystemWatcher with the console application带有控制台应用程序的 FileSystemWatcher
【发布时间】:2019-07-06 13:46:17
【问题描述】:

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

我计划用控制台应用程序而不是 Windows 服务或调度程序来编写文件观察器。

我已将可执行文件快捷方式复制到以下路径中。

%appdata%\Microsoft\Windows\开始菜单\程序

参考: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);

【问题讨论】:

  • 你有没有让你的程序在开始观看后以MAIN的方式等待?
  • 我在这里提出疑问,什么是正确的观看方法。是的,我已经在 main 方法中等待。
  • 您的代码似乎是正确的,但您应该知道它只监视文件在 root 中,不是文件在 sub-folders 中.
  • 谢谢。我将检查并添加该条件。这里我有两个问题。所以我需要添加代码 [new System.Threading.AutoResetEvent(false).WaitOne(); ] 总是被观看.. 我想知道为什么我们应该只看根文件夹而不是子文件夹?。

标签: c# file-watcher


【解决方案1】:

由于是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。 p>

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

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

【讨论】:

  • 我将只检查仅添加到特定文件夹的 xml 文件(这种情况偶尔会发生),并且我使用 NotifyFilter 只知道文件名,我将只检查根文件夹。这也会产生缓冲区溢出。
  • @JeevaJsb 文件多久更改一次?如果它如此频繁,那么你必须增加InternalBufferSize,就像我上面提到的那样。
猜你喜欢
  • 2016-12-20
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 2010-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多