• Vizteck Author

How To Create a Window Service in

Window Service creates executable applications that run in its own Window Session. Depending upon the configuration setting, they can start manually or automatically when the computer starts. I’ll explain step by step on how to create a Window Service in C#.Net

  • Click File -> New Project.

  • Select Window Service Template.

  • Name the service MyWindowService.

  • Rename the Service1.cs to MyService.cs.

  • Add Event log to the Service , by click tool and dropingEventLog.

  • Rename the eventLog1 to EventLog4MyService.'

  • Right Click the MyService.cs and select View designer.

  • In the designer window right click and click Add “Add Installer”.

  • Select serviceProcessInstaller1 and in property window, adjust the fields as in the below figure.

Right click MyService and select code. Type the following code.

publicMyService(){InitializeComponent();if(!System.Diagnostics.EventLog.SourceExists("Source4MyService")){EventLog4MyService.Source = "Source4MyService";EventLog4MyService.Log = "Log4MyService";}EventLog4MyService.Source = "Source4MyService";EventLog4MyService.Log = "Log4MyService";}protectedoverridevoidOnStart(string[] args){EventLog4MyService.WriteEntry("OnStrart method is called at time: " + DateTime.Now);}protectedoverridevoidOnStop(){EventLog4MyService.WriteEntry("OnStop() method is called at time: " + DateTime.Now);}

How To Build and Deploy the Service

1. Right Click the MyWindowService project and select properties.

2. Select the Target FrameWork. (in my case it is 4.5)

3. Select targetplateform (in my case x64).

Type PostBuild Events Commands

XCOPY $(ProjectDir)\bin\debug\*.exe C:\Temp\MyExecutables
This command will copy the service with .exe extension to C:\Temp\MyExecutables folder%WinDir%\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /u $(ProjectDir)bin\Debug\MyWindowService.exe

This command will uninstall

“MyWindowService.exe%WinDir%\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe $(ProjectDir)bin\Debug\MyWindowService.exe 

 This command will install MyWindowService.exe.

Now Build the project. If the build is successful, the service will also be installed.

Alternative way to Deploy the service:

Create a file in the notepad, and type the following script

Echo Installing the MyServiceC:\Windows\\v4\installutil.exe (target file path)Pause

Save the file as “install.bat”.To uninstall the service, use the following script in another Uninstall.bat file

Echo Uninstalling the Service.C:\Windows\\v4\installutil.exe /u (target file path)Pause

Running the file as administrator will install the service.Type services.msc and go to services and run the service.

(Window Service “MyService” has successfully installed)