0

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 + "]: ");
Simon MᶜKenzie
  • 8,344
  • 13
  • 50
  • 77
Soulzityr
  • 406
  • 1
  • 8
  • 26

3 Answers3

4

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);
    }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • This doesn't work. I get an I/o Exception that the file is being used by another process, but this is the only part of my code that interacts with the file right now. – Soulzityr Apr 04 '14 at 20:16
  • Then you have another instance of your program running or something like that. This is _your_ code, just refactored so that it can be called in the `using` block. The code works exactly the same way. – John Saunders Apr 04 '14 at 20:21
1

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.

Tolga Evcimen
  • 7,112
  • 11
  • 58
  • 91
0

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)

Will Newton
  • 1,583
  • 13
  • 10