In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to add file monitoring service to C#Windows service". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to add file monitoring service to C#Windows service".
First, we open Visual Studio.Net and create a new Windows service project for Visual C#, as shown in the figure:
Before overloading the OnStart () function of the Windows service, let's add some counter objects to its class that correspond to file creation, deletion, renaming, and modification. Once any of the above changes occur to the files in the specified directory, the corresponding counter will be automatically incremented by 1. All of these counters are defined as variables of type PerformanceCounter, which are included in the System.Diagnostics namespace.
Private System.Diagnostics.PerformanceCounter fileCreateCounter; private System.Diagnostics.PerformanceCounter fileDeleteCounter; private System.Diagnostics.PerformanceCounter fileRenameCounter; private System.Diagnostics.PerformanceCounter fileChangeCounter
We then create each counter object defined above in the InitializeComponent () method of the class and determine its relevant properties. At the same time, we set the name of the Windows service to "FileMonitorService", which allows both pausing and resuming and stopping.
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;}
Then the OnStart () function and the OnStop () function are overloaded, and the OnStart () function does some necessary initialization. Under the .net framework, file monitoring can be done by the FileSystemWatcher class, which is included in the System.IO namespace. The functions to be completed by the Windows service include monitoring file creation, deletion, renaming, and modification, and the FileSystemWatcher class contains all the handlers corresponding to these changes.
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 ();}
Note that the directory being monitored is stored in an application configuration file, which is a file of type XML. The advantage of this approach is that we do not have to recompile and publish the Windows service, but simply modify its configuration file to change the directory to be monitored.
When the Windows service starts, once the files in the monitored directory change, the value of the counter corresponding to it will increase accordingly. The method is simple, as long as you call IncrementBy () of the counter object.
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);}}
The OnStop () function stops the Windows service. In this Windows service, once the service stops, the value of all counters should return to zero, but the counter does not provide a Reset () method, so we have to subtract the current value from the counter to achieve this.
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);}}
Note that adding a file monitoring service to the C#Windows service: because our Windows service allows pausing and resuming, we also have to overload the OnPause () function and the OnContinue () function, simply by setting the Boolean value servicePaused defined earlier.
Protected override void OnPause () {servicePaused = true;} protected override void OnContinue () {servicePaused = false;}
In this way, the body of the Windows service is complete, but it is not useful, and we must add installation file monitoring to it. The installation file, which does the work for the correct installation of the Windows service, includes an installation class for the Windows service, which is inherited from System.Configuration.Install.Installer. The installation class includes account information, user name, password information, Windows service name, startup mode and other information needed for the operation of the Windows service.
[RunInstaller (true)] public class Installer1: System.Configuration.Install.Installer {/ required designer variables. / private System.ComponentModel.Container components = null; private System.ServiceProcess.ServiceProcessInstaller spInstaller; private System.ServiceProcess.ServiceInstaller sInstaller; public Installer1 () {/ / this call is required by the designer. InitializeComponent (); / / TODO: add any initialization} # region Component Designer generated code / designer support required methods after the InitComponent call-do not use the code editor to modify / the contents of this method. / / private void InitializeComponent () {components = new System.ComponentModel.Container (); / / create ServiceProcessInstaller object and ServiceInstaller object this.spInstaller = new System.ServiceProcess.ServiceProcessInstaller (); this.sInstaller = new System.ServiceProcess.ServiceInstaller (); / / set account, user name and password of ServiceProcessInstaller object this.spInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem; this.spInstaller.Username = null; this.spInstaller.Password = null / / set the service name this.sInstaller.ServiceName = "FileMonitorService"; / / set the service startup mode this.sInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; this.Installers.AddRange (new System.Configuration.Install.Installer [] {this.spInstaller, this.sInstaller});} # endregion}
Similarly, because the counter object is used in the Windows service, we also need to add the corresponding installation file, which is similar in content and function to the previous one. Due to the limited space, the corresponding code is not given here, and interested readers can refer to the source code file attached to the article.
At this point, the entire Windows service has been built, but unlike a normal application, the Windows service cannot be debugged and run directly. If you try to debug and run it directly under IDE, you will be prompted as shown in the figure.
According to the tips, we know that a command line tool called InstallUtil.exe is needed to install the Windows service. Using this tool to install the Windows service is very simple. The command to install the Windows service is as follows:
Installutil FileMonitorService.exe
To uninstall the Windows service, you can simply enter the following command:
Installutil / u FileMonitorService.exe
After the Windows service is successfully installed, it appears in the service control manager, as shown in the figure.
In this way, the C#Windows service monitored by the file is completed, and once we operate on the files in the monitored directory, the corresponding counter will operate to monitor file changes. However, this function does not make much sense to the average user, however, you can add new features on this basis, such as building a background file processing system, once the files in the monitored directory change, the Windows service will perform specific operations on it, and the end user does not have to care about how the background processor is implemented.
Thank you for reading, the above is the content of "how to add file monitoring service to C#Windows service". After the study of this article, I believe you have a deeper understanding of how to add file monitoring service to C#Windows service. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.