Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

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

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 =)

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top