Timer Objects in Windows Services with C#.NET - Adding Code
(Page 3 of 5 )
1. Switch to the code view of the Service1.cs file.
Note: we renamed the service to TimerSrv, so we need to change the Run command in the Main method of this class. Find the following line:
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new Service1() };
Now, change this to the following:
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new TimerSrv() };
2. In the top of the file add use statements:
Use System.IO;
// we need this to write to the file
use System.Timers;
//we need this to create the timer.
3. Somewhere in the class, add a new private void AddToFile() method. We will use this to write text to a file.
private void AddToFile(string contents)
{
//set up a filestream
FileStream fs = new
FileStream(@”c:\timerserv.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(contents);
//add the text to the underlying filestream
sw.Flush();
//close the writer
sw.Close();
}
Now we can start coding the events.
Next: Coding the Windows Service Start and Stop Event Handlers >>
More C# Articles
More By Rogier Doekes
|
| · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | | |
|