August 29th, 2010

Create Windows Service quickly using .NET

Generally some tasks are required to be scheduled or dependent on the time. So this can be performed easily using windows service. Here are the steps to create windows service quickly.


1. File-> New Project -> Visual C# -> Windows -> Windows Services
Give Project Name and location.

2. Now Right Click -> View code
Here is the sample code which writes in the log file on particular interval.


public partial class Service1 : ServiceBase
    {
        private Timer timer1 = null;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new Timer(); 
            this.timer1.Interval = 6000;
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled = true;                
            Log("Timer Started");
             
        }

        protected override void OnStop()
        {
            timer1.Enabled = false; 
            Log("Timer Closed");
             
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Log("test");
        }
        public static void Log(string str)
        {
            StreamWriter Tex = File.AppendText(@"c:\Backuplog.txt");
            Tex.WriteLine(DateTime.Now.ToString() + " " + str);
            Tex.Close();

        }
  }

3. Now Right click on this Page-> View Designer
windows service
Right Click -> Add Installer
It will automatically create projectinstaller.cs of this service.

4. Build this project. It will create exe of this project. Now this is to be installed in windows services using installutil.exe which is available in .NET Framework location. To Do this quickly, Create a batch file in notepad, First Uninstall exising service then install the service else you will get error. See following(Suppose exe name is SchService.exe) then in batch file for .NET Framework 2.0:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /u ” SchService.exe”
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe ” SchService.exe”

5. Run this batch file from command prompt.

6. You can test this service. Right Click of My Computer -> Computer Management ->Services->Select Service and Right Click -> Start

7. Then you will see log file in c:\bakuplog.txt as we implemented in the service. It will generate a log in each 6 sec. so, close the service after some time.

If you want to start this service automatically, open projectinstaller.cs and add following line after InitializeComponent in the constructor:

serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;

Hope, It helps.