使用Streamwriter在Visual Basic中写入新行

时间:2017-03-11 09:28:02

标签: vb.net newline streamwriter streamwriter.write

每次按"按钮2" 应该从各种文本框中获取数据并将其写入我的文本文件中。由于某些未知原因,程序只是覆盖了文本文件中的所有内容,而我需要它来写入新行。如果有人知道怎么做,请告诉我!

请参阅以下代码:

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 个答案:

答案 0 :(得分:1)

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

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

我还将变量objreader更改为更接近它正在做的事情,我再次建议您这样做以使代码更具可读性。

答案 1 :(得分:1)

使用StreamWriter(String, Boolean) constructor指定是要附加还是覆盖文件。

最好还将StreamWriter包裹在Using block中,而不是拨打Close()

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