• Unfortunately, we have experienced significant hard drive damage that requires urgent maintenance and rebuilding. The forum will be a state of read only until we install our new drives and rebuild all the configurations needed. Please follow our Facebook page for updates, we will be back up shortly! (The forum could go offline at any given time due to the nature of the failed drives whilst awaiting the upgrades.) When you see an Incapsula error, you know we are in the process of migration.

[C#] Creating a Windows Service

Junior Spellweaver
Joined
Nov 26, 2008
Messages
196
Reaction score
62
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:

Code:
System.IO.StreamWrite file;

protected override void OnStart(string[] args)
{
    // create or open the file. Default path is "C:\windows\System32\"
    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, add using System.ServiceProcess, and the following code to the constructor:

Code:
ServiceInstaller si = new ServiceInstaller();
ServiceProcessInstaller spi = new ServiceProcessInstaller();

si.ServiceName = "Service1"; // this must match the ServiceName specified in WindowsService1.
si.DisplayName = "Tutorial Service"; // this will be displayed in the Services Manager.
this.Installers.Add(si);

spi.Account = System.ServiceProcess.ServiceAccount.LocalSystem; // run under the system account.
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 "Tutorial Service" to the Services Manager.