TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Creating a Windows Services in C#
Husain Ahmedabadwala
May 09
2015
Code
5.2
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Diagnostics;
using
System.IO;
using
System.Linq;
using
System.ServiceProcess;
using
System.Text;
using
System.Threading;
using
System.Threading.Tasks;
using
System.Timers;
namespace
MyWinService
{
public
partial
class
Service1: ServiceBase
{
public
Service1()
{
InitializeComponent();
}
//************************************************************************************************************
//Initialize the timer
System.Timers.Timer timer =
new
System.Timers.Timer();
//************************************************************************************************************
//This method is used to raise event during start of service
protected
override
void
OnStart(
string
[] args)
{
//add this line to text file during start of service
TraceService(
"Start service"
);
//handle Elapsed event
timer.Elapsed +=
new
ElapsedEventHandler(OnElapsedTime);
//This statement is used to set interval to 30 Seconds (= 30,000 milliseconds)
timer.Interval = 30000;
//enabling the timer
timer.Enabled =
true
;
}
//************************************************************************************************************
//This method is used to stop the service
protected
override
void
OnStop()
{
timer.Enabled =
false
;
TraceService(
"Stopping service"
);
}
//************************************************************************************************************
private
void
OnElapsedTime(
object
source, ElapsedEventArgs e)
{
TraceService(
"Another entry at "
+ DateTime.Now);
}
//************************************************************************************************************
private
void
TraceService(
string
content)
{
//set up a filestream
FileStream fs =
new
FileStream(@
"d:\Service1.txt"
, FileMode.OpenOrCreate, FileAccess.Write);
//set up a streamwriter for adding text
StreamWriter sw =
new
StreamWriter(fs);
//find the end of the underlying filestream
sw.BaseStream.Seek(0, SeekOrigin.End);
//add the text
sw.WriteLine(content);
//add the text to the underlying filestream
sw.Flush();
//close the writer
sw.Close();
}
//************************************************************************************************************
}
}
Windows Service
Create Service in Windows