2016-11-29 111 views
1

要在我的Web应用程序中发送批量电子邮件我正在使用filewatcher发送应用程序。FileSystemWatcher与控制台应用程序

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

我已经复制了以下路径中的可执行文件快捷方式。

%APPDATA%\微软\的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); 
+0

开始观看后,您是否已使程序在'MAIN'方法中等待? –

+0

我在这里质疑什么是正确的观察方法。 是的,我已经等待主要方法。 –

+0

你的代码似乎是正确的,但你应该知道它只监视文件在'root'中,而不是**文件在'子文件夹中'。 –

回答

4

因为它是你需要写在Main方法的代码等,不属于运行代码后立即关闭Console Application

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

你的代码只,如果你想看着你需要设置IncludeSubdirectories=true为您守望对象的子文件夹跟踪在root文件夹的变化,

 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属性,以便过滤掉不需要的更改 通知。

+0

我将仅检查仅添加到特定文件夹的xml文件(这将偶尔发生),并且我已经使用NotifyFilter仅知道文件名,我将仅检查根文件夹。所以这会导致缓冲区溢出。 –

+0

@JeevaJsb文件多久改变一次?如果它非常频繁,那么你必须像上面提到的那样增加'InternalBufferSize'。 –

+0

谢谢。 : - ).... –