我在方法之外编写了这段代码,因为我需要在 OnStop() 方法中关闭并处理流写入器和文件流:
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
但是新的StreamWriter里面的fs提示错误“A field initializer cannot reference the non-static field, method, or property..”。所以我将 FileStream 设为静态:
private static FileStream fs = new FileStream(@"D:\Hello.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
当我运行程序时,它没有写入文本文件并得出结论,这是因为静态。我搜索并阅读:“一个类可以声明为静态,表明它只包含静态成员。使用 new 关键字无法创建静态类的实例。静态类由 .NET Framework 自动加载加载包含该类的程序或命名空间时的公共语言运行时 (CLR)。”
这是我的示例代码:
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();
}
}
你觉得我应该怎么做?