I made this code outside the methods because I need to close and dispose the streamwriter and filestream in the OnStop() method:
private Timer timer = new Timer();
private FileStream fs = new FileStream(@"D:\Hello.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
private StreamWriter sw = new StreamWriter(fs);
//The fs is in red line, having error
However, the fs inside the new StreamWriter prompts the error "A field initializer cannot reference the non-static field, method, or property..". So I made the FileStream static:
private static FileStream fs = new FileStream(@"D:\Hello.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
When I ran the program, it doesn't write to the textfile and concluded that it's because of the static. I searched about it and read this: "A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded."
This is my sample code:
public partial class Service1 : ServiceBase
{
private Timer timer = new Timer();
private FileStream fs = new FileStream(@"D:\Hello.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
private StreamWriter sw = new StreamWriter(fs);
//The fs is in red line, having error. Look in my description for error's details
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer.Elapsed += new ElapsedEventHandler(WriteText);
timer.Interval = 5000; //5 seconds
timer.Start();
}
public void WriteText(object source, ElapsedEventArgs e)
{
sw.WriteLine(DateTime.Now + " Windows Service");
}
protected override void OnStop()
{
sw.Close();
sw.Dispose();
fs.Close();
fs.Dispose();
timer.Stop();
}
}
What do you think should I do?