Soulzityr
Soulzityr

Reputation: 456

StreamWriter won't write to log file

This code will create "output.txt" in C:\temp if it doesn't already exist. However, log.WriteLine(); doesn't work for me. When I open the file, I don't see it. Why is this?

private static string LogFile = @"C:\Temp\output.txt";
private StreamWriter log;
if (!File.Exists(@"" + LogFile))
{
    log = new StreamWriter(@"" + LogFile);
}
else {
    log = File.AppendText(@"" + LogFile);
}
log.WriteLine("["+DateTime.Now + "]: ");

Upvotes: 0

Views: 2672

Answers (3)

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

Just a little improvement in code to @John Saunders answer.

using (var log = GetLog())
{
    log.WriteLine("["+DateTime.Now + "]: ");
}

...

public StreamWriter GetLog()
{
    return new StreamWriter(LogFile, File.Exists(LogFile));
}

The second parameter StreamWriter constructer takes determines append operation. Thus if file exists append otherwise not will do it. I think this is neater. And actually you can even do:

using (var log = new StreamWriter(LogFile, true))
{
    log.WriteLine("["+DateTime.Now + "]: ");
}

Always appends, and if file does not exist creates it.

Upvotes: 1

Will N
Will N

Reputation: 1610

If you are always appending the same thing to the file whether or not it already exists, you don't need the conditional.

File.AppendText will create the file if it doesn't exist.

private static string LogFile = @"C:\Temp\output.txt";

using (StreamWriter sw = File.AppendText(LogFile)) 
{
    sw.WriteLine("["+DateTime.Now + "]: ");
}

As John Saunders already said, you need to Dispose the stream writer, which will be done by putting it in a using statement.

(Documentation for StreamWriter)

Upvotes: 0

John Saunders
John Saunders

Reputation: 161773

You need to close the StreamWriter. It's best to use a using block for this, as it guarantees that the StreamWriter will be closed, even if an exception is thrown.

using (var log = GetLog()){
    log.WriteLine("["+DateTime.Now + "]: ");
}

...

public StreamWriter GetLog(){
    if (!File.Exists(@"" + LogFile))
    {
        return new StreamWriter(@"" + LogFile);
    }
    else {
        return File.AppendText(@"" + LogFile);
    }
}

Upvotes: 4

Related Questions