无法写入已关闭的TextWriter

时间:2012-08-14 10:46:28

标签: textwriter

我有错误,

  

“无法写入已关闭的TextWriter。”

代码:

public class Logs
{
    static string File_Path= "";
    static public FileStream fs;
    static public StreamWriter sw;
    public static void Initialize(string path)
    {
        File_Path = path;

        fs = new FileStream(File_Path, FileMode.Append, FileAccess.Write);
        sw = new StreamWriter(fs);
    }
    public static void info_log(string msg)
    {                      
        sw.WriteLine("{0} [INFO] : {1}",DateTime.Now.ToString(),msg);
        sw.WriteLine(" ");
        sw.Close();
        sw.Flush();
    }
    public static void error_log(Exception ex)
    {
        sw.WriteLine("{0} [ERROR] : {1}", DateTime.Now.ToString(), ex.Message);
        sw.WriteLine("StackTrace : {0}:", ex.StackTrace);
        sw.WriteLine(" ");
        sw.Close();
        sw.Flush();
    }
    public static void warning_log(string msg)
    {
        sw.WriteLine("{0} [WARNING] : {1}", DateTime.Now.ToString(), msg);
        sw.WriteLine(" ");
        sw.Close();
        sw.Flush();
    }
}

1 个答案:

答案 0 :(得分:2)

嗯,你正在关闭StreamWriter,然后在每次写入后刷新它。换句话说,您关闭流然后尝试写入它。

通常,您需要初始化一次,然后使用日志记录方法。写完之后只需要sw.Flush()。 (所以......在每种方法中删除sw.Close()。)

但是,如果您的应用程序仅在极少数情况下记录消息,则会在每次调用之前初始化(因为这种情况很少发生)并在刷新后关闭。这需要重新排序sw.Flush()sw.Close()