Thursday, April 7, 2011

Create Window Services using C#

Step 1: Open a new Window Service Project

Start Microsoft Visual Studio, (I have used 2010) Select Add a new project and select Windows Service and select a language of your preference,(i have used C#) give a suitable name to your project and click ok.
Now in the solution explorer you will see a WindowService.cs file, rename it to some name you can remember (eg: your name).

Step 2: Functions OnStart(), OnStop().
As you can see in the web service .cs file, there are two overridden functions OnStart and OnStop. The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service.

protected override void OnStart(string[] args)
protected override void OnStop()

I am opening a notepad.exe” application when this services is started and opening a “paint” application when this service is stopped, this i am doing for us just to understand when a service is started and stopped.

Step3 :Install and Run the Service

Before installing the service be sure to add an installer, by right clicking on the .cs file and selecting the add new installer option, after which two components will be added : serviceProcessInstaller and serviceInstaller, now goto the serviceProcessInstaller properties tab and change the Account property to LocalService !
Build this application, a .exe file will be created in your debug folder, now Access the directory in which your project’s compiled executable file is located.
Run InstallUtil.exe from the command line with your project’s output as a parameter. Enter the following code on the command line:
installutil yourproject.exe
installutil /u yourproject.exe

The second command is used when you want to uninstall the service.
(In some cases you may get an error as installutil is not a recognised command or so, if such error occurs then simply use the full path of installutil.exe as C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\installutil followed by the applicationName.exe)

Step 4: Start and Stop the Service

You need to go to the Computer Management to Start to start and stop the service. You can use Manage menu item by right clicking on My Computer.
Under Services and Applications,  after clicking on services tabyou will see the service yasserService.

Start the service and Stop the service.


Post a Comment


2011 ·Code-Studio by yrus.