471,317 Members | 1,842 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,317 software developers and data experts.

Logginh Function

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

Feb 7 '06 #1
4 1047
Are you possibly calling the same method from different threads?

Feb 7 '06 #2
Steven, Form1.echo is used by several classes in the same application,
it get called from many instances of these classes.

Feb 7 '06 #3
Mr. Bean wrote:
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
Feb 7 '06 #4
worked just fine.. Thanks

Feb 7 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by domeceo | last post: by
5 posts views Thread by phil_gg04 | last post: by
2 posts views Thread by laredotornado | last post: by
2 posts views Thread by sushil | last post: by
8 posts views Thread by Olov Johansson | last post: by
3 posts views Thread by Beta What | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.