c# - Writing log to a text file not working as expected -


i have log class given below.

public  class log {     public  streamwriter logfile     { get; set; }      public  string logfilepath = environment.getenvironmentvariable("temp")+"\\testlog.txt";      public  string logfilepath     {                 {             return logfilepath;         }         set         {             value = logfilepath;         }     }      public  void writelog(string logmessage)     {         try         {             if (!file.exists(logfilepath))             {                 logfile = new streamwriter(logfilepath);             }             else             {                 logfile = file.appendtext(logfilepath);             }              logfile.writeline(datetime.now);             logfile.writeline(logmessage.tostring());             logfile.writeline();             logfile.flush();         }         catch         {         }     } } 

i called above writelog function in log class using object given below.

log lg = new log(); lg.writelog("message1"); lg.writelog("message2"); lg.writelog("message3"); lg.writelog("message4"); 

issue "message1" added log. other other messages not written.

how can solve this?

your problem not closing log file, when write next time it's still open (because garbage collector hasn't run yet , closed you).

that means exception subsequent calls logging function, hiding empty catch (which bad!).

you must close or dispose file. best way enclose in using. means don't need flush either (because closing/disposing filestream flush first).

a using ensure closes if exception occurs. in fact, think can simplify whole thing this:

public void writelog(string logmessage) {     using (var logfile = file.appendtext(logfilepath))     {         logfile.writeline(datetime.now);         logfile.writeline(logmessage);         logfile.writeline();     } } 

file.appendtext() create new file if 1 doesn't exist, don't need check first.

and empty catch had. never that. @ least log exception message. if had done that, have seen exception occurring, , have seen - , have told going wrong.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

javascript - Clean way to programmatically use CSS transitions from JS? -

android - send complex objects as post php java -