Tuesday, August 7, 2012

Create Windows Service using C#.NET

1) Create a console Application in .NET and name it "WinServiceTest"

2) Create a class to write data to file as given below


    public class TestWriteFile
    {
        public static bool Shutdown = false;
        Thread fileWriteThread;
        public static void WriteCurentTime()
        {
            while (Shutdown == false)
            {
                string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(TestWriteFile)).CodeBase).Replace("file:\\","");
                using (FileStream ofs = File.Open(path + "\\test.txt", FileMode.Append))
                {
                    UTF8Encoding enc = new UTF8Encoding();
                    String tmpstr = DateTime.Now.ToString() + "\n";
                    ofs.Write(enc.GetBytes(tmpstr), 0, enc.GetByteCount(tmpstr));
                    ofs.Close();
                }
                Thread.Sleep(10000);//sleep for 10 seconds
            }
        }
        public void StartProcess()
        {
            fileWriteThread = new Thread(new ThreadStart(WriteCurentTime));
            fileWriteThread.Start();
        }
        public void StopProcess()
        {
            Shutdown = true;
            fileWriteThread.Join();
        }
    }


3) Add reference to System.ServiceProcess

4) Add service class WinServiceTestService.cs which inherits from ServiceBase.cs


public class WinServiceTestService: ServiceBase
    {
        TestWriteFile oprocessor;
        public static void Main(string[] args)
        {
            ServiceBase.Run(new WinServiceTestService());
        }
        public WinServiceTestService()
        {
            this.ServiceName = "My Win Service Test";
        }
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            oprocessor = new TestWriteFile();
            oprocessor.StartProcess();
        }
        protected override void OnStop()
        {
            base.OnStop();
            oprocessor.StopProcess();
        }
    }




Ok... now we have to create the installer to install the service.

5) Add reference to System.Configuration.Install

6) Write Code for installer as given below


using System.Configuration.Install;
using System.ComponentModel;
using System.ServiceProcess;

namespace WinServiceTest
{
    [RunInstaller(true)]
    public class WinServiceTestInstaller : Installer
    {
        public WinServiceTestInstaller()
        {
            var processInstaller = new ServiceProcessInstaller();
            var serviceInstaller = new ServiceInstaller();

            // Service Account Information
            processInstaller.Account = ServiceAccount.LocalSystem;
            processInstaller.Username = null;
            processInstaller.Password = null;

            serviceInstaller.DisplayName = "My Win Service Test Process";
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            serviceInstaller.ServiceName = "My Win Service Test Process";

            this.Installers.Add(processInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }
}




7) Remove "static" from the "Main" function in Program.cs file

We are done! Windows service is ready. Now we have to install it. For installing we can use 'InstallUtil'.

Open Visual Studio command window and type "installutil /i WinServiceTest.ext" to install the service

To Start the service, open service manager right click on the task "My Win Service..." and click 'Start'

No comments: