我正在尝试写入顺序访问文件,但每次单击“写入”按钮时,将从文件中删除第一个列表框选择并添加新的列表框选择,如何解决此问题?
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles Me.Load
'fills list box with parties
partyListBox.Items.Add("Democrat")
partyListBox.Items.Add("Republican")
partyListBox.Items.Add("Independent")
End Sub
Private Sub writeButton_Click(sender As Object, e As EventArgs) Handles writeButton.Click
Dim outFile As IO.StreamWriter
Dim party As String = partyListBox.SelectedItem.ToString
Dim age As Integer
Integer.TryParse(ageTextBox.Text, age)
outFile = IO.File.CreateText("politicalparties.txt")
'write to file
outFile.WriteLine(party & ", " & age)
'close file
outFile.Close()
End Sub
答案 0 :(得分:1)
您可以执行以下操作,在文件末尾附加一行文字:
Using sw As StreamWriter = File.AppendText("politicalparties.txt")
sw.WriteLine(party & ", " & age)
End Using
如果该文件尚不存在,则会创建该文件。