Hi,
Following are the steps to create a basic windows service to write a file in .net:
include following namespaces:
using System.Text;
using System.IO;
using System.Timers;
Create a class level timer:
private Timer timer = new Timer();
On Start Event:
protected override void OnStart(string[] args)
{
timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
timer.Interval = 10000;
timer.Enabled = true;
}
Create Event handler:
private void TimerElapsed(object source, ElapsedEventArgs e)
{
Logger();
}
Create function:
public void Logger()
{
string mydocument =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string[] txtList = Directory.GetFiles(mydocument, "*.txt");
StringBuilder sb = new StringBuilder();
string FileName = @"\log.txt";
using (StreamReader sr = new StreamReader(mydocument + FileName))
{
sb.AppendLine(DateTime.Now.ToString());
sb.AppendLine("---------------------------------------------");
sb.Append(sr.ReadToEnd());
sb.AppendLine();
}
using (StreamWriter outfile =
new StreamWriter(mydocument + FileName))
{
outfile.Write(sb.ToString());
}
}
InstallUtil command to install the service:
installutil ServicePath/Servicename.exe
To uninstall the service:
installutil /u ServicePath/Servicename.exe
No comments:
Post a Comment