Cannot write to a closed TextWriter

7.1k views Asked by At

I have a error,

"Cannot write to a closed TextWriter."

Code:

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

There are 1 answers

0
Tadas S On

Well, you are closing the StreamWriter, and THEN flushing it after each write. In other words, you close the stream and then try to write to it.

Typically you would want to initialize once and then use the logging methods. That would only need a sw.Flush() after writing. (So... remove that sw.Close() in each method).

However, if your application only logs messages under some very rare circumstances, you would initialize before each call (since that happens so rarely) and close after flushing. That would need a reorder of sw.Flush() and sw.Close().