1

我有一个错误,

“无法写入已关闭的 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();
    }
}
4

1 回答 1

2

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

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

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

于 2012-08-15T06:05:09.963 回答