首页 > 解决方案 > 如何将文本附加到文本文件?

问题描述

我想将文本框中的文本写入文本文件。

代码写入文本文件的第一行。当我清除文本框以写入其他值时,之前写入的内容消失并被新值替换。

如何获得要写入前一个值的新值集?

Dim path As String = TextBox1.Text & ".txt"
path = "C:\Users\USER\Desktop\" & path

Dim studentno As Integer = TextBox2.Text
Dim name As String = TextBox3.Text
Dim surname As String = TextBox4.Text
Dim subject As String = TextBox8.Text
Dim indv As Integer = TextBox5.Text
Dim grp As Integer = TextBox6.Text
Dim test As Integer = TextBox7.Text

If System.IO.File.Exists(path) = True Then
    Dim sw As New System.IO.StreamWriter(path)
    sw.WriteLine(studentno & "," & name & "," & surname & "," & subject & "," & indv & "," & grp & "," & test)
    sw.Close()
    MessageBox.Show("Text written to file.", "Note", MessageBoxButtons.OK, MessageBoxIcon.Information)

Else
    MessageBox.Show("File Does Not Exist.", "Note", MessageBoxButtons.OK, MessageBoxIcon.Information)

End If

End Sub

标签: vbatext-files

解决方案


这是我必须创建文件的代码,它工作得很好,所以这很好。


 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim path As String = TextBox1.Text & ".txt"
        path = "C:\Users\USER\Desktop\" & path

        If String.IsNullOrEmpty(TextBox1.Text) = True Then
            MessageBox.Show("Textbox Empty", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
        ElseIf Not File.Exists(path) Then
            File.Create(path).Dispose()
            MessageBox.Show("File created.", "Note", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            MessageBox.Show("File already exists.", "Note", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

    End Sub


推荐阅读