-1

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
4

2 回答 2

1

您需要附加文本,并且通过使用该Using语句,它负责对象的处置,允许对象干净地终止其资源,我建议您使用。

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

我还将变量更改为objreader与其正在执行的操作更相关的内容,我再次建议您这样做以使代码更具可读性。

于 2017-03-11T09:32:27.183 回答
1

使用StreamWriter(String, Boolean)构造函数来指定是要追加还是覆盖文件。

最好也将您包装StreamWriter在一个Using中,而不是调用Close().

Using objreader As New System.IO.StreamWriter(filename, True) 'True = append.
    objreader.WriteLine(username & "," & password & "," & forename & "," & surname & "," & dob & "," & phone & "," & address & ",")
End Using
于 2017-03-11T09:34:45.787 回答