microsoft windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own windows sessions. these services can be automatically started when the computer boots. can be paused and restarted, and do not show any user interface. these features make services ideal for use on a server or whenever you need long-running functionality that dose not interfere with other users who are working on the same computer.
step1. create project
once click ok, the below screen will appare which is your service
step 2: add installers to the service
right click on the blank area and select "add installer."
after adding installer, projectinstaller will add in your project and ProjectInstakker.cs file will be open.
select serviceinstaller1 than edit description and service name that show at windows service management futher .
select serviceProcessInstaller1
from properties modify account to LocalSystem, and save all.
step3 in this step we will implement a timer, and code to call a service at a given time. we will create a simple write in a text file
service1 calls:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Timers;
namespace MyFirstService
{
public partial class Service1 : ServiceBase
{
Timer timer = new Timer();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 5000; //number in milisecinds
timer.Enabled = true;
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
WriteToFile("Service is recall at " + DateTime.Now);
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}
build your application.
step 4 . install service to computer
opent "command prompt" as administrator account
route to the below path
go to your application file path,and fire the below command, if successful like screen catch
open windows service management , start the service
now we can see the Log file was generated
step 5. if want uninstall the service can use <InstallUtil.exe -u c:\Debug\MyFirstService.exe>