| |
In this tutorial, I will go construct a simple windows service in C# that writes to a file whenever it is started or stopped.
Create a new Windows Service C# Project titled "WindowsService1". Visual Studio.NET will create a project with a class that extends the System.ServiceProcess.ServiceBase class. This class contains methods for controlling the process; OnStart(), OnStop(), OnPause(), and OnContinue(). The start and stop methods are required and the other are optional. Add using System.IO; and add the following code to the file:
System.IO.StreamWrite file;
protected override void OnStart(string[] args)
{
file = new StreamWriter( new FileStream("ServiceTest.log", System.IO.FileMode.Append ) );
this.file.WriteLine("Starting Service");
this.file.Flush();
}
protected override void OnStop()
{
this.file.WriteLine("Stopping Service");
this.file.Flush();
this.file.Close();
}
|
Next you must create an installer class. The installer class sets the configuration for the Service and for the Service Processes. These specify the display name of the service and the account that will run the process. Create a new Installer class (see above image), add using System.ServiceProcess;, and the following code to the constructor:
ServiceInstaller si = new ServiceInstaller();
ServiceProcessInstaller spi = new ServiceProcessInstaller();
si.ServiceName = "Service1";
si.DisplayName = "Devhood Tutorial Service";
this.Installers.Add(si);
spi.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
spi.Password = null;
spi.Username = null;
this.Installers.Add(spi);
|
The service must be installed before it can execute. Services are installed with "installutil.exe" and uninstalled with "installutil.exe /u" with the service executable as the last parameter. For example, "installutil.exe C:\project\WindowsService1\bin\WindowsService1.exe" will install the service and then the "Devhood Tutorial Service" to the Services Manager.
After the service is installed, it can be started and stopped from the Services Section of Computer Management.
The source files could be found here.
|
|