Menu ▼


Creating first windows service

In our first windows service, we will create a service which will write the service start time and stop time in a log file in the location C:\servicelog.txt

  • Open visual studio
  • Select windows service template in create new porject

    windows service template
  • Give service name as Windows Service Example, select the location and click on OK
  • Right Click on Service1.cs and select view code
  • Write this sample code in Service1.cs
    string fileLocation = "C:\\servicelog.txt";
    protected override void OnStart(string[] args)
    {
        if (!File.Exists(fileLocation))
            File.Create(fileLocation).Close();
        File.AppendAllText(fileLocation, "Service started : " + DateTime.Now.ToString() + Environment.NewLine);
    }

    protected override void OnStop()
    {
        File.AppendAllText(fileLocation, "Service stoped : " + DateTime.Now.ToString() + Environment.NewLine);
    }
  • sample code






comments powered by Disqus


Search dotnetlearners.com