-1

I'm designing a new server application, which includes a subroutine that parses the input into the console window, for example

LogAlways("--- CPU detection ---")

will be written as:

[net 21:8:38.939] --- CPU detection ---

This is the subroutine:

Public Sub LogAlways(ByVal input As String)
    Dim dm As String = "[net " + Date.Now.Hour.ToString + ":" + Date.Now.Minute.ToString + ":" + Date.Now.Second.ToString + "." + Date.Now.Millisecond.ToString + "] "
    Console.WriteLine(dm + input)
    Dim fName As String = Application.StartupPath() + "\LogBackups\" + Date.Now.Day.ToString + Date.Now.Month.ToString + "" + Date.Now.Year.ToString + ".log"
    Dim stWt As New Global.System.IO.StreamWriter(fName)
    stWt.Write(dm + input)
    stWt.Close()
End Sub

This works, but however only the last line of my desired input is written to the file.

Why is this happening, and how can I make it so that it does not overwrite the log file? This is using the Wildfire Server API.

This is not a duplicate, as the destination question has a different answer which would otherwise not answer this question.

AStopher
  • 4,207
  • 11
  • 50
  • 75
  • *I made this question for the endless trail of newbies that ask the same question over and over again.* – AStopher Jun 01 '15 at 20:24
  • possible duplicate of [How to append text to an existing text file](http://stackoverflow.com/questions/9141866/how-to-append-text-to-an-existing-text-file) – Rowland Shaw Sep 02 '15 at 09:33
  • @RowlandShaw Nope, read the destination question & its answers. – AStopher Sep 02 '15 at 09:35

1 Answers1

1

This occurs as the StreamWriter has not been told to append the output to the end of the file with the parameter set to True, Visual Studio actually gives it as a version of the StreamWriter:

enter image description here

To correctly declare it:

Dim stWt As New Global.System.IO.StreamWriter(fName, True)

or in the subroutine:

Public Sub LogAlways(ByVal input As String)
    Dim dm As String = "[net " + Date.Now.Hour.ToString + ":" + Date.Now.Minute.ToString + ":" + Date.Now.Second.ToString + "." + Date.Now.Millisecond.ToString + "] "
    Console.WriteLine(dm + input)
    Dim fName As String = Application.StartupPath() + "\LogBackups\" + Date.Now.Day.ToString + Date.Now.Month.ToString + "" + Date.Now.Year.ToString + ".log"
    Dim stWt As New Global.System.IO.StreamWriter(fName, True)
    stWt.Write(dm + input)
    stWt.Close()
End Sub

Requires the following to be Imports:

  • System.IO
  • System.Windows.Forms

It will now correctly write to the end of the file, but however it is noted that stWt.Close()'ing the file on every call may cause issues, therefore a queuing system may be better:

  • Desired log output is inserted into a single-dimensional array
  • A Timer dumps this array to the log file on every, say, five to ten seconds
  • When this is done, the array is cleared
AStopher
  • 4,207
  • 11
  • 50
  • 75