溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#Windows服務(wù)中怎么添加文件監(jiān)視服務(wù)

發(fā)布時(shí)間:2021-12-02 11:56:13 來源:億速云 閱讀:173 作者:iii 欄目:編程語言

這篇文章主要講解了“C#Windows服務(wù)中怎么添加文件監(jiān)視服務(wù)”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“C#Windows服務(wù)中怎么添加文件監(jiān)視服務(wù)”吧!

首先,我們打開Visual Studio.Net,新建一個(gè)Visual C#的Windows服務(wù)的項(xiàng)目,如圖所示:

C#Windows服務(wù)中怎么添加文件監(jiān)視服務(wù)

在重載Windows服務(wù)的OnStart()函數(shù)之前,我們先給其類添加一些計(jì)數(shù)器對象,這些計(jì)數(shù)器分別對應(yīng)了文件的創(chuàng)建、刪除、改名以及修改等變化。一旦指定目錄中的文件發(fā)生以上的某種變化,與其相對應(yīng)的計(jì)數(shù)器就會自動加1。所有的這些計(jì)數(shù)器都是定義為PerformanceCounter類型的變量的,該類是包含在System.Diagnostics命名空間中的。

private System.Diagnostics.PerformanceCounter fileCreateCounter;   private System.Diagnostics.PerformanceCounter fileDeleteCounter;   private System.Diagnostics.PerformanceCounter fileRenameCounter;   private System.Diagnostics.PerformanceCounter fileChangeCounter;

之后我們便在類的InitializeComponent()方法中創(chuàng)建以上定義的各個(gè)計(jì)數(shù)器對象并確定其相關(guān)屬性。同時(shí)我們將該Windows服務(wù)的名稱設(shè)置為“FileMonitorService”,設(shè)定其即是允許暫停并恢復(fù)的又是允許停止的。

private void InitializeComponent()    {   this.components = new System.ComponentModel.Container();   this.fileChangeCounter = new System.Diagnostics.PerformanceCounter();   this.fileDeleteCounter = new System.Diagnostics.PerformanceCounter();   this.fileRenameCounter = new System.Diagnostics.PerformanceCounter();   this.fileCreateCounter = new System.Diagnostics.PerformanceCounter();    fileChangeCounter.CategoryName = "File Monitor Service";   fileDeleteCounter.CategoryName = "File Monitor Service";   fileRenameCounter.CategoryName = "File Monitor Service";   fileCreateCounter.CategoryName = "File Monitor Service";       fileChangeCounter.CounterName = "Files Changed";   fileDeleteCounter.CounterName = "Files Deleted";   fileRenameCounter.CounterName = "Files Renamed";   fileCreateCounter.CounterName = "Files Created";    this.ServiceName = "FileMonitorService";   this.CanPauseAndContinue = true;   this.CanStop = true;   servicePaused = false;    }

接著就是重載OnStart()函數(shù)和OnStop()函數(shù),OnStart()函數(shù)完成了一些必要的初始化工作。在.Net框架下,文件的監(jiān)視功能可以由FileSystemWatcher類來完成,該類是包含在System.IO命名空間下的。該Windows服務(wù)所要完成的功能包括了監(jiān)視文件的創(chuàng)建、刪除、改名和修改等變化,而FileSystemWatcher類包含所有了對應(yīng)于這些變化的處理函數(shù)。

protected override void OnStart(string[] args)    {        FileSystemWatcher curWatcher = new FileSystemWatcher();    curWatcher.BeginInit();   curWatcher.IncludeSubdirectories = true;   curWatcher.Path =   System.Configuration.ConfigurationSettings.AppSettings   ["FileMonitorDirectory"];   curWatcher.Changed += new FileSystemEventHandler(OnFileChanged);   curWatcher.Created += new FileSystemEventHandler(OnFileCreated);   curWatcher.Deleted += new FileSystemEventHandler(OnFileDeleted);   curWatcher.Renamed += new RenamedEventHandler(OnFileRenamed);   curWatcher.EnableRaisingEvents = true;   curWatcher.EndInit();    }

注意其中被監(jiān)視的目錄是存放在一個(gè)應(yīng)用程序配置文件中的,該文件是一個(gè)XML類型的文件。這種做法的好處就是我們不必重新編譯并發(fā)布該Windows服務(wù)而只要直接修改其配置文件就可以達(dá)到更改所要監(jiān)視的目錄的功能了。

當(dāng)該Windows服務(wù)啟動后,一旦被監(jiān)視的目錄中的文件發(fā)生某種變化,與其相對應(yīng)的計(jì)數(shù)器的值便會相應(yīng)的增加,方法很簡單,只要調(diào)用計(jì)數(shù)器對象的IncrementBy()即可。

private void OnFileChanged(Object source, FileSystemEventArgs e)    {   if( servicePaused == false )   {     fileChangeCounter.IncrementBy(1);   }    }    private void OnFileRenamed(Object source, RenamedEventArgs e)    {   if( servicePaused == false )   {     fileRenameCounter.IncrementBy(1);   }    }        private void OnFileCreated(Object source, FileSystemEventArgs e)    {   if( servicePaused == false )   {     fileCreateCounter.IncrementBy(1);   }    }    private void OnFileDeleted(Object source, FileSystemEventArgs e)    {   if( servicePaused == false )   {     fileDeleteCounter.IncrementBy(1);   }    }

OnStop()函數(shù)即是停止Windows服務(wù)的,在該Windows服務(wù)中,服務(wù)一旦停止,所有的計(jì)數(shù)器的值都應(yīng)歸零,但是計(jì)數(shù)器并不提供一個(gè)Reset()方法,所以我們只好將計(jì)數(shù)器中的值減去當(dāng)前值來達(dá)到這個(gè)目的。

protected override void OnStop()    {   if( fileChangeCounter.RawValue != 0 )   {     fileChangeCounter.IncrementBy(-fileChangeCounter.RawValue);   }   if( fileDeleteCounter.RawValue != 0 )   {     fileDeleteCounter.IncrementBy(-fileDeleteCounter.RawValue);   }   if( fileRenameCounter.RawValue != 0 )   {     fileRenameCounter.IncrementBy(-fileRenameCounter.RawValue);         }   if( fileCreateCounter.RawValue != 0 )   {     fileCreateCounter.IncrementBy(-fileCreateCounter.RawValue);   }    }

C#Windows服務(wù)中添加文件監(jiān)視服務(wù)需要注意的:因?yàn)槲覀兊腤indows服務(wù)是允許暫停并恢復(fù)的,所以我們還得重載OnPause()函數(shù)和OnContinue()函數(shù),方法很簡單,只要設(shè)定前面定義的布爾值servicePaused即可。

protected override void OnPause()    {   servicePaused = true;    }   protected override void OnContinue()    {   servicePaused = false;   }

這樣,該Windows服務(wù)的主體部分已經(jīng)完成了,不過它并不有用,我們還必須為其添加安裝文件監(jiān)視。安裝文件為Windows服務(wù)的正確安裝做好了工作,它包括了一個(gè)Windows服務(wù)的安裝類,該類是重System.Configuration.Install.Installer繼承過來的。安裝類中包括了Windows服務(wù)運(yùn)行所需的帳號信息,用戶名、密碼信息以及Windows服務(wù)的名稱,啟動方式等信息。

[RunInstaller(true)]   public class Installer1 : System.Configuration.Install.Installer    {    /// <summary>    /// 必需的設(shè)計(jì)器變量。    /// </summary>    private System.ComponentModel.Container components = null;   private System.ServiceProcess.ServiceProcessInstaller spInstaller;   private System.ServiceProcess.ServiceInstaller sInstaller;    public Installer1()    {   // 該調(diào)用是設(shè)計(jì)器所必需的。   InitializeComponent();   // TODO: 在 InitComponent 調(diào)用后添加任何初始化    }    #region Component Designer generated code    /// <summary>    /// 設(shè)計(jì)器支持所需的方法 - 不要使用代碼編輯器修改    /// 此方法的內(nèi)容。    /// </summary>   private void InitializeComponent()    {   components = new System.ComponentModel.Container();   // 創(chuàng)建ServiceProcessInstaller對象和ServiceInstaller對象   this.spInstaller =    new System.ServiceProcess.ServiceProcessInstaller();   this.sInstaller = new System.ServiceProcess.ServiceInstaller();   // 設(shè)定ServiceProcessInstaller對象的帳號、用戶名和密碼等信息   this.spInstaller.Account =    System.ServiceProcess.ServiceAccount.LocalSystem;   this.spInstaller.Username = null;   this.spInstaller.Password = null;          // 設(shè)定服務(wù)名稱   this.sInstaller.ServiceName = "FileMonitorService";              // 設(shè)定服務(wù)的啟動方式   this.sInstaller.StartType =    System.ServiceProcess.ServiceStartMode.Automatic;    this.Installers.AddRange(   new System.Configuration.Install.Installer[]    {this.spInstaller, this.sInstaller });    }    #endregion          }

同樣,因?yàn)樵揥indows服務(wù)中運(yùn)用到了計(jì)數(shù)器對象,我們也要為其添加相應(yīng)的安裝文件,安裝文件的內(nèi)容和作用與前面的類似。限于篇幅,這里就不給出相應(yīng)的代碼了,有興趣的讀者可以參考文后附帶的源代碼文件。

到此為止,整個(gè)Windows服務(wù)已經(jīng)構(gòu)建完畢,不過Windows服務(wù)程序和一般的應(yīng)用程序不同,它不能直接調(diào)試運(yùn)行。如果你直接在IDE下試圖調(diào)試運(yùn)行之,就會報(bào)出如圖所示提示。

C#Windows服務(wù)中怎么添加文件監(jiān)視服務(wù)

根據(jù)其中提示,我們知道安裝Windows服務(wù)需要用到一個(gè)名為InstallUtil.exe的命令行工具。而運(yùn)用該工具安裝Windows服務(wù)的方法是非常簡單的,安裝該Windows服務(wù)的命令如下:

installutil FileMonitorService.exe

而要卸載該Windows服務(wù),你只要輸入如下的命令即可:

installutil /u FileMonitorService.exe

Windows服務(wù)安裝成功后,它便會出現(xiàn)在服務(wù)控制管理器中,如圖所示。

C#Windows服務(wù)中怎么添加文件監(jiān)視服務(wù)

這樣,該文件監(jiān)視的C#Windows服務(wù)就完成了,一旦我們對被監(jiān)視的目錄中的文件進(jìn)行操作,相應(yīng)的計(jì)數(shù)器就會運(yùn)作,起到監(jiān)視文件變化的作用。不過這個(gè)功能對于一般的用戶而言沒多大意義,然而你可以在此基礎(chǔ)上添加新的功能,比如構(gòu)建一個(gè)后臺的文件處理系統(tǒng),一旦被監(jiān)視的目錄中的文件發(fā)生某種變化,Windows服務(wù)便對其進(jìn)行特定的操作,而最終用戶就不必去關(guān)心后臺處理程序是如何實(shí)現(xiàn)的了。

感謝各位的閱讀,以上就是“C#Windows服務(wù)中怎么添加文件監(jiān)視服務(wù)”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對C#Windows服務(wù)中怎么添加文件監(jiān)視服務(wù)這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI