How to append to a text file in VB.Net

I am trying to write a simple vb program that takes input from a form and writes to a text file.  I have tried to work it out using xml and I have not had much luck, so I have decided to go back to writing to a text file.  Here is what I have so far, my problem is that the program will not append to the file. It just keeps overwriting the first line.  If their is a better way to code this, could someone please explain.

Thanks

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click
        Dim oFile As System.IO.File
        Dim objWriter As System.IO.StreamWriter
        objWriter = oFile.CreateText("\my documents\data.txt")
        Dim stop_time As Date = Now
   
        Dim FILE_NAME As String = "\my documents\data.txt"

        If System.IO.File.Exists(FILE_NAME) = True Then



            objWriter.Write((Eq_Num.Text) + ",")
            objWriter.Write((ComboBox1.Text) + ",")
            objWriter.Write((ComboBox2.Text) + ",")
            objWriter.Write((ComboBox3.Text) + ",")
            objWriter.Write((ComboBox4.Text) + ",")
            objWriter.Write((ComboBox5.Text) + ",")
            objWriter.Write((ComboBox6.Text) + ",")
            objWriter.WriteLine((stop_time) + ",")
            objWriter.Flush()
            objWriter.Close()
            MsgBox("Text written to file")

        Else
            MsgBox("File Does Not Exist")
        End If

       
    End Sub
maximjonAsked:
Who is Participating?
 
bobbit31Commented:
instead of oFile.CreateTEext(...) try using:

oFile.AppendText("\my documents\data.txt")
0
 
heintalusCommented:
Try changing it to the following that way it will also create the file if it doesn't exist

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click

        Dim objWriter As System.IO.StreamWriter
        Dim stop_time As Date = Now
        Dim FILE_NAME As String = "\my documents\data.txt"

        If System.IO.File.Exists(FILE_NAME) = True Then
            objWriter = System.IO.File.AppendText(FILE_NAME)
        Else
            objWriter = System.IO.File.CreateText(FILE_NAME)
        End If

        objWriter.Write((Eq_Num.Text) + ",")
        objWriter.Write((ComboBox1.Text) + ",")
        objWriter.Write((ComboBox2.Text) + ",")
        objWriter.Write((ComboBox3.Text) + ",")
        objWriter.Write((ComboBox4.Text) + ",")
        objWriter.Write((ComboBox5.Text) + ",")
        objWriter.Write((ComboBox6.Text) + ",")
        objWriter.WriteLine((stop_time) + ",")
        objWriter.Flush()
        objWriter.Close()

        MsgBox("Text written to file")
       
End Sub

HTH
Andy
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.