Reputation: 13
I've a functioning streamwriter that creates a text file and places the information I need in that file, but whenever I re-run the application the text file is created anew with the current values replacing the old. How do I ensure that previous data is saved in the text file with the new data being added on to it? Appending the data to the file seems to be the obvious route, but I'm just not sure how to incorporate the code for that into my program.
Dim CorpID, Fname, Lname, PreConf, ConfCost As String
CorpID = txtCorpID.Text
Fname = txtFirstName.Text
Lname = txtLastName.Text
If radNotAttending.Checked = True Then
PreConf = ""
Else
PreConf = cmbCourses.SelectedItem.ToString
End If
ConfCost = decAttendCost.ToString("C")
Dim wr As StreamWriter
wr = New StreamWriter("C:\Users\Anon\Documents\SampleTextFile.txt")
wr.WriteLine(String.Format("{0},{1},{2},{3}, {4}", CorpID, Fname, Lname, PreConf, ConfCost))
wr.Flush()
wr = Nothing
Upvotes: 0
Views: 7477
Reputation: 710
You need another Overload of the StreamWriter Constructor.
Just use wr = New StreamWriter("C:\Users\Anon\Documents\SampleTextFile.txt", true)
You need this one
Example:
Using wr As new StreamWriter("C:\Users\Anon\Documents\SampleTextFile.txt",true)
wr.WriteLine($"{CorpID},{Fname},{Lname},{PreConf},{ConfCost})
End Using
With using
, StreamWriter
is released when done with it, so when you click the button again, no StreamWriter
is accessing the file and you can create another insatnce of StreamWriter
without problems.
Upvotes: 1
Reputation: 219077
There's an overload of the StreamWriter
constructor for exactly this purpose:
wr = New StreamWriter("C:\Users\Anon\Documents\SampleTextFile.txt", True)
The second parameter is:
true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.
Upvotes: 0