初始化服务类中的FileStream和StreamWriter字段

时间:2012-08-24 08:15:34

标签: c# static

我在方法之外创建了这段代码,因为我需要在OnStop()方法中关闭并处理streamwriter和filestream:

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会提示错误“字段初始化程序无法引用非静态字段,方法或属性..”。所以我将FileStream设为静态:

private static FileStream fs = new FileStream(@"D:\Hello.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

当我运行程序时,它不会写入文本文件并得出结论是因为静态。我搜索了它并阅读this:“一个类可以声明为静态,表明它只包含静态成员。不可能使用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();
    }
}

您认为我应该怎么做?

3 个答案:

答案 0 :(得分:4)

你所做的应该工作正常,但这不是一个好方法,所以不值得调查它为什么不起作用。在类中使用静态变量不会使类静态。

只需声明没有初始化器的变量,然后在要打开文件时设置变量:

public partial class Service1 : ServiceBase
{
    private Timer timer;
    private FileStream fs;
    private StreamWriter sw

    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        fs = new FileStream(@"D:\Hello.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
        sw = new StreamWriter(fs);
        timer = new Timer();
        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()
    {
        timer.Stop(); // Stop the timer before closing the file
        sw.Close();
        sw.Dispose();
        fs.Close();
        fs.Dispose();
    }
}

答案 1 :(得分:3)

不要让它们变得静止。只需将初始化代码从字段初始化器移动到构造函数即可。并且不要忘记添加一个处理它们的Dispose方法。

答案 2 :(得分:2)

您不需要静态字段,只需将初始化移动到构造函数:

private FileStream fs;
private StreamWriter sw;

public MyClass()
{
    fs = new FileStream(@"D:\Hello.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite); 
    sw = new StreamWriter(fs);
}

为了确保您的OnStop()方法真正被调用并且流已被处理,请在您的班级中实施IDisposable并在OnStop()方法结束时致电Dispose()