Writing to a new line in Visual Basic with Streamwriter

5.3k Views Asked by At

Every time I press "button2" it should take the data from various text boxes and write them into my text file on a new line. For some unknown reason, the program just overwrites everything in the text file, whereas I need it to write to a new line. If someone knows how to do this please let me know!

Refer the below Code:

Public Class Form5
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.Hide()
    Form2.Show()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Dim username As String = (TextBox1.Text & TextBox2.Text)
    Dim password As String = "password"
    Dim forename As String = TextBox1.Text
    Dim surname As String = TextBox2.Text
    Dim dob As String = TextBox3.Text
    Dim phone As String = TextBox4.Text
    Dim address As String = TextBox5.Text
    Dim filename As String = "../../usernamepassword.txt"
    Dim objreader As New System.IO.StreamWriter(filename)
    objreader.WriteLine(username & "," & password & "," & forename & "," & surname & "," & dob & "," & phone & "," & address & ",")
    objreader.Close()
End Sub
2

There are 2 best solutions below

0
Asons On

You need to append text, and by using the Using statement, it takes care of the disposal of the object, allowing the object to cleanly terminate its resources, which I recommend you use.

Using sw As StreamWriter = File.AppendText(filename)
  sw.WriteLine(username & "," & password & "," & forename & "," & surname & "," & dob & "," & phone & "," & address & ",")
End Using

I also changed the variable objreader to something more relative to what it is doing, again I recommend you do like that to make the code more readable.

2
Visual Vincent On

Use the StreamWriter(String, Boolean) constructor to specify whether you want to append to or overwrite the file.

Preferrably also wrap your StreamWriter in a Using block instead of calling Close().

Using objreader As New System.IO.StreamWriter(filename, True) 'True = append.
    objreader.WriteLine(username & "," & password & "," & forename & "," & surname & "," & dob & "," & phone & "," & address & ",")
End Using