Logginh Function

M

Mr. Bean

Hi,
I use a simple static funtion to output errors, trace messages...
However when i call the same function more than one I get an error that
the text file is used by another application..

public static void echo(string logMessage){
StreamWriter w = File.AppendText("log.txt");
DateTime d = DateTime.Now;
w.WriteLine(d.ToString()+logMessage);
w.Flush();
w.Close();
w = null;
}

//call the fucntion Form1.echo ("error message");

What am I doing wrong? Is there a better way...
 
M

Mr. Bean

Steven, Form1.echo is used by several classes in the same application,
it get called from many instances of these classes.
 
S

Scott C

Mr. Bean said:
public static void echo(string logMessage){
StreamWriter w = File.AppendText("log.txt");
DateTime d = DateTime.Now;
w.WriteLine(d.ToString()+logMessage);
w.Flush();
w.Close();
w = null;
}

//call the fucntion Form1.echo ("error message");

What am I doing wrong? Is there a better way...
I think you aren't Close()ing the file. A better way, would be to do
something like this (compiles but untested):

public static void echo(string logMessage){
using(StreamWriter w = File.AppendText("log.txt")) {
w.Write(DateTime.Now);
w.WriteLine(logMessage);
}
}

Check out the "using" keyword in msdn somewhere. It's really nice for
stuff like this. I also changed the date+string to two different writes
with the idea that no string concatenation is better (someone correct me
if I'm wrong).

Scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top