views:

552

answers:

5

I've got a very small standalone vb.net app that gets run automatically. Every now and then it hits an error condition that I want to log and then keep processing. But, this is far too minor a thing to store in the system's main log - I really just want to append a line to a text file.

What's the least stress way to append a line of text to a file (and have it create the file if it's not there) under .net?

+1  A: 

This MSDN article, How to: Write Text to a File should do it.

cciotti
+14  A: 

IO.File.AppendAllText(@"Y:\our\File\Name.here", "your log message here")

Joel Coehoorn
cciotti
In what way is it dirty? It's certainly simple - but it does exactly what's required (assuming UTF-8 is okay).
Jon Skeet
w00t! This answer put me in the 5-digit club (just beat you there, Jon)
Joel Coehoorn
I'm only 700 behind :D
FlySwat
closer to 600 now- going quick
Joel Coehoorn
Oh, that's spectaular, and exactly what I was looking for but couldn't get MSDN to tell me about. Also: glad I could help get into 5 digit space, Joel. Thanks.
Electrons_Ahoy
+2  A: 

This is in C#, but should be trivial to change to VB:

    void logMessage(string message)
    {
        string logFileName = "log.file";

        File.AppendAllText(logFileName,message);
    }

Edited because Joel's solution was much simpler than mine =)

FlySwat
+3  A: 

In VB.NET, My.Computer.FileSystem.WriteAllText will do the trick. If you don't like the My namespace, System.IO.File.AppendAllText works as well.

Mark Brackett
+2  A: 
Private Const LOG_FILE As String = "C:\Your\Log.file"

Private Sub AppendMessageToLog(ByVal message As String)
    If Not File.Exists(LOG_FILE) Then
        File.Create(LOG_FILE)
    End If

    Using writer As StreamWriter = File.AppendText(LOG_FILE)
        writer.WriteLine(message)
    End Using
End Sub
Bullines