C#Windows服务之添加文件监视服务

开发 后端
C#Windows服务中添加文件监视服务是如何实现的呢?C#Windows服务中添加文件监视服务需要注意什么呢?让我们带着这些问题看一下的文章。

C#Windows服务之添加文件监视服务:

了解了Windows服务的基本体系结构和创建方法后,我们就可以试着往服务中添加一些实际的功能了。下面我将向大家介绍一个能监视本地文件系统的文件监视服务-FileMonitorService。该服务能根据预先设定的本地目录路径监视其中的文件包括子文件夹中的任何变化:文件创建、文件删除、文件改名、文件修改。同时,该服务还为每种变化创建了一个相对应的计数器,计数器的作用就是反映该种变化的频度。

首先,我们打开Visual Studio.Net,新建一个Visual C#的Windows服务的项目,如图所示:

新建C#的Windows服务的项目 

在重载Windows服务的OnStart()函数之前,我们先给其类添加一些计数器对象,这些计数器分别对应了文件的创建、删除、改名以及修改等变化。一旦指定目录中的文件发生以上的某种变化,与其相对应的计数器就会自动加1。所有的这些计数器都是定义为PerformanceCounter类型的变量的,该类是包含在System.Diagnostics命名空间中的。

  1. private System.Diagnostics.PerformanceCounter fileCreateCounter;  
  2.  
  3. private System.Diagnostics.PerformanceCounter fileDeleteCounter;  
  4.  
  5. private System.Diagnostics.PerformanceCounter fileRenameCounter;  
  6.  
  7. private System.Diagnostics.PerformanceCounter fileChangeCounter; 

之后我们便在类的InitializeComponent()方法中创建以上定义的各个计数器对象并确定其相关属性。同时我们将该Windows服务的名称设置为“FileMonitorService”,设定其即是允许暂停并恢复的又是允许停止的。

  1. private void InitializeComponent()  
  2.  
  3.  {  
  4.  
  5. this.components = new System.ComponentModel.Container();  
  6.  
  7. this.fileChangeCounter = new System.Diagnostics.PerformanceCounter();  
  8.  
  9. this.fileDeleteCounter = new System.Diagnostics.PerformanceCounter();  
  10.  
  11. this.fileRenameCounter = new System.Diagnostics.PerformanceCounter();  
  12.  
  13. this.fileCreateCounter = new System.Diagnostics.PerformanceCounter();  
  14.  
  15.  
  16. fileChangeCounter.CategoryName = "File Monitor Service";  
  17.  
  18. fileDeleteCounter.CategoryName = "File Monitor Service";  
  19.  
  20. fileRenameCounter.CategoryName = "File Monitor Service";  
  21.  
  22. fileCreateCounter.CategoryName = "File Monitor Service";  
  23.  
  24.    
  25.  
  26. fileChangeCounter.CounterName = "Files Changed";  
  27.  
  28. fileDeleteCounter.CounterName = "Files Deleted";  
  29.  
  30. fileRenameCounter.CounterName = "Files Renamed";  
  31.  
  32. fileCreateCounter.CounterName = "Files Created";  
  33.  
  34.  
  35. this.ServiceName = "FileMonitorService";  
  36.  
  37. this.CanPauseAndContinue = true;  
  38.  
  39. this.CanStop = true;  
  40.  
  41. servicePaused = false;  
  42.  
  43.  } 

接着就是重载OnStart()函数和OnStop()函数,OnStart()函数完成了一些必要的初始化工作。在.Net框架下,文件的监视功能可以由FileSystemWatcher类来完成,该类是包含在System.IO命名空间下的。该Windows服务所要完成的功能包括了监视文件的创建、删除、改名和修改等变化,而FileSystemWatcher类包含所有了对应于这些变化的处理函数。

  1. protected override void OnStart(string[] args)  
  2.  
  3.  {       
  4.  
  5. FileSystemWatcher curWatcher = new FileSystemWatcher();  
  6.  
  7.  
  8. curWatcher.BeginInit();  
  9.  
  10. curWatcher.IncludeSubdirectories = true;  
  11.  
  12. curWatcher.Path =  
  13.  
  14. System.Configuration.ConfigurationSettings.AppSettings  
  15.  
  16. ["FileMonitorDirectory"];  
  17.  
  18. curWatcher.Changed += new FileSystemEventHandler(OnFileChanged);  
  19.  
  20. curWatcher.Created += new FileSystemEventHandler(OnFileCreated);  
  21.  
  22. curWatcher.Deleted += new FileSystemEventHandler(OnFileDeleted);  
  23.  
  24. curWatcher.Renamed += new RenamedEventHandler(OnFileRenamed);  
  25.  
  26. curWatcher.EnableRaisingEvents = true;  
  27.  
  28. curWatcher.EndInit();  
  29.  
  30.  } 

注意其中被监视的目录是存放在一个应用程序配置文件中的,该文件是一个XML类型的文件。这种做法的好处就是我们不必重新编译并发布该Windows服务而只要直接修改其配置文件就可以达到更改所要监视的目录的功能了。

当该Windows服务启动后,一旦被监视的目录中的文件发生某种变化,与其相对应的计数器的值便会相应的增加,方法很简单,只要调用计数器对象的IncrementBy()即可。

  1. private void OnFileChanged(Object source, FileSystemEventArgs e)  
  2.  
  3.  {  
  4.  
  5. if( servicePaused == false )  
  6.  
  7. {  
  8.  
  9.   fileChangeCounter.IncrementBy(1);  
  10.  
  11. }  
  12.  
  13.  }  
  14.  
  15.  private void OnFileRenamed(Object source, RenamedEventArgs e)  
  16.  
  17.  {  
  18.  
  19. if( servicePaused == false )  
  20.  
  21. {  
  22.  
  23.   fileRenameCounter.IncrementBy(1);  
  24.  
  25. }  
  26.  
  27.  }  
  28.  
  29.    
  30.  
  31.  private void OnFileCreated(Object source, FileSystemEventArgs e)  
  32.  
  33.  {  
  34.  
  35. if( servicePaused == false )  
  36.  
  37. {  
  38.  
  39.   fileCreateCounter.IncrementBy(1);  
  40.  
  41. }  
  42.  
  43.  }  
  44.  
  45.  private void OnFileDeleted(Object source, FileSystemEventArgs e)  
  46.  
  47.  {  
  48.  
  49. if( servicePaused == false )  
  50.  
  51. {  
  52.  
  53.   fileDeleteCounter.IncrementBy(1);  
  54.  
  55. }  
  56.  
  57.  } 

 

OnStop()函数即是停止Windows服务的,在该Windows服务中,服务一旦停止,所有的计数器的值都应归零,但是计数器并不提供一个Reset()方法,所以我们只好将计数器中的值减去当前值来达到这个目的。

  1. protected override void OnStop()  
  2.  
  3.  {  
  4.  
  5. if( fileChangeCounter.RawValue != 0 )  
  6.  
  7. {  
  8.  
  9.   fileChangeCounter.IncrementBy(-fileChangeCounter.RawValue);  
  10.  
  11. }  
  12.  
  13. if( fileDeleteCounter.RawValue != 0 )  
  14.  
  15. {  
  16.  
  17.   fileDeleteCounter.IncrementBy(-fileDeleteCounter.RawValue);  
  18.  
  19. }  
  20.  
  21. if( fileRenameCounter.RawValue != 0 )  
  22.  
  23. {  
  24.  
  25.   fileRenameCounter.IncrementBy(-fileRenameCounter.RawValue);        
  26.  
  27. }  
  28.  
  29. if( fileCreateCounter.RawValue != 0 )  
  30.  
  31. {  
  32.  
  33.   fileCreateCounter.IncrementBy(-fileCreateCounter.RawValue);  
  34.  
  35. }  
  36.  
  37.  } 

C#Windows服务中添加文件监视服务需要注意的:因为我们的Windows服务是允许暂停并恢复的,所以我们还得重载OnPause()函数和OnContinue()函数,方法很简单,只要设定前面定义的布尔值servicePaused即可。

  1. protected override void OnPause()  
  2.  
  3.  {  
  4.  
  5. servicePaused = true;  
  6.  
  7.  }  
  8.  
  9. protected override void OnContinue()  
  10.  
  11.  {  
  12.  
  13. servicePaused = false;  
  14.  

这样,该Windows服务的主体部分已经完成了,不过它并不有用,我们还必须为其添加安装文件监视。安装文件为Windows服务的正确安装做好了工作,它包括了一个Windows服务的安装类,该类是重System.Configuration.Install.Installer继承过来的。安装类中包括了Windows服务运行所需的帐号信息,用户名、密码信息以及Windows服务的名称,启动方式等信息。

  1. [RunInstaller(true)]  
  2.  
  3. public class Installer1 : System.Configuration.Install.Installer  
  4.  
  5.  {  
  6.  
  7.  /// <summary>  
  8.  
  9.  /// 必需的设计器变量。  
  10.  
  11.  /// </summary>  
  12.  
  13.  private System.ComponentModel.Container components = null;  
  14.  
  15. private System.ServiceProcess.ServiceProcessInstaller spInstaller;  
  16.  
  17. private System.ServiceProcess.ServiceInstaller sInstaller;  
  18.  
  19.  public Installer1()  
  20.  
  21.  {  
  22.  
  23. // 该调用是设计器所必需的。  
  24.  
  25. InitializeComponent();  
  26.  
  27. // TODO: 在 InitComponent 调用后添加任何初始化  
  28.  
  29.  }  
  30.  
  31.  #region Component Designer generated code  
  32.  
  33.  /// <summary>  
  34.  
  35.  /// 设计器支持所需的方法 - 不要使用代码编辑器修改  
  36.  
  37.  /// 此方法的内容。  
  38.  
  39.  /// </summary>  
  40.  
  41. private void InitializeComponent()  
  42.  
  43.  {  
  44.  
  45. components = new System.ComponentModel.Container();  
  46.  
  47. // 创建ServiceProcessInstaller对象和ServiceInstaller对象  
  48.  
  49. this.spInstaller =   
  50.  
  51. new System.ServiceProcess.ServiceProcessInstaller();  
  52.  
  53. this.sInstaller = new System.ServiceProcess.ServiceInstaller();  
  54.  
  55. // 设定ServiceProcessInstaller对象的帐号、用户名和密码等信息  
  56.  
  57. this.spInstaller.Account =   
  58.  
  59. System.ServiceProcess.ServiceAccount.LocalSystem;  
  60.  
  61. this.spInstaller.Username = null;  
  62.  
  63. this.spInstaller.Password = null;  
  64.  
  65.        // 设定服务名称  
  66.  
  67. this.sInstaller.ServiceName = "FileMonitorService";  
  68.  
  69.    
  70.  
  71.        // 设定服务的启动方式  
  72.  
  73. this.sInstaller.StartType =   
  74.  
  75. System.ServiceProcess.ServiceStartMode.Automatic;  
  76.  
  77.  
  78. this.Installers.AddRange(  
  79.  
  80. new System.Configuration.Install.Installer[]   
  81.  
  82. {this.spInstaller, this.sInstaller });  
  83.  
  84.  }  
  85.  
  86.  #endregion  
  87.  
  88.        } 

同样,因为该Windows服务中运用到了计数器对象,我们也要为其添加相应的安装文件,安装文件的内容和作用与前面的类似。限于篇幅,这里就不给出相应的代码了,有兴趣的读者可以参考文后附带的源代码文件。

到此为止,整个Windows服务已经构建完毕,不过Windows服务程序和一般的应用程序不同,它不能直接调试运行。如果你直接在IDE下试图调试运行之,就会报出如图所示提示。

Windows服务程序报出提示 

根据其中提示,我们知道安装Windows服务需要用到一个名为InstallUtil.exe的命令行工具。而运用该工具安装Windows服务的方法是非常简单的,安装该Windows服务的命令如下:

  1. installutil FileMonitorService.exe 

而要卸载该Windows服务,你只要输入如下的命令即可:

  1. installutil /u FileMonitorService.exe 

Windows服务安装成功后,它便会出现在服务控制管理器中,如图所示。

Windows服务安装成功 

这样,该文件监视的C#Windows服务就完成了,一旦我们对被监视的目录中的文件进行操作,相应的计数器就会运作,起到监视文件变化的作用。不过这个功能对于一般的用户而言没多大意义,然而你可以在此基础上添加新的功能,比如构建一个后台的文件处理系统,一旦被监视的目录中的文件发生某种变化,Windows服务便对其进行特定的操作,而最终用户就不必去关心后台处理程序是如何实现的了。

C#Windows服务中添加文件监视服务的相关内容就向你介绍到这里,希望对你学习和了解C#Windows服务中添加文件监视服务有所帮助。

【编辑推荐】

  1. C#复制构造函数的实质浅析
  2. C#允许服务与桌面交互实现浅析
  3. C#windows服务中的Timer控件的使用
  4. C#Windows服务介绍
  5. C#创建Windows服务程序浅析
责任编辑:仲衡 来源: vchome.net
相关推荐

2009-08-14 13:41:13

C#Windows服务

2009-08-14 15:19:38

Windows服务程序Windows服务

2009-08-14 10:50:09

Windows服务介绍

2009-08-14 16:48:39

C#Windows服务

2009-08-14 14:25:09

Windows服务程序

2009-08-14 14:53:55

WINDOWS服务交互

2009-08-14 15:06:08

Windows服务程序

2009-08-14 15:47:18

C#Windows服务

2009-08-14 15:54:50

Windows服务程序C#Windows服务

2009-08-14 14:17:16

C#Windows服务

2009-08-14 16:24:00

Windows服务程序

2009-08-14 16:13:25

C#windows服务

2009-08-14 14:45:03

C#Windows服务

2009-08-14 17:55:52

C#Windows应用

2009-08-14 17:43:20

C#Windows应用

2009-08-14 10:42:16

Timer控件的使用C#windows服务

2009-08-14 17:27:30

C#Windows应用

2009-08-14 17:51:32

C#Windows应用

2009-08-14 18:04:59

C#Windows应用

2009-08-14 17:36:20

C#Windows应用
点赞
收藏

51CTO技术栈公众号