1

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();
    }
}
Musakkhir Sayyed
  • 7,012
  • 13
  • 42
  • 65
sezer ural
  • 11
  • 1
  • 2
  • Can you give us an example of the order in which you call these methods? Because if you don't call Initialize before each call og info_log, error_log or warning_log, you actually try to write using a CLOSED StreamWriter. You need to open the StreamWriter before any WriteLine operation. – Coral Doe Aug 14 '12 at 10:51
  • If initialization was not called, then `sw` would be `null`, resulting in a NPE. – Tadas S Aug 15 '12 at 05:59

1 Answers1

2

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().

Tadas S
  • 1,955
  • 19
  • 33