.

Appending Text to a File in VB .NET

There will be times when you won't want to erase all the text from your file. You'll only want to add text to what you currently have. In which case you need to Append.
Appending text to your file is quite easy.
When you set up the object variable for the Stream Writer, , you just typed the name and path of the file:
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
To append text to a file, you type a comma after your file name then type the word True:
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
If you want to add some text to the file, you need that True value. If you leave out the True or False, a new file is not created.
Here some code that appends text to the file we wrote to:

Dim FILE_NAME As String = "C:\test.txt"
Dim i As Integer
Dim aryText(4) As String

aryText(0) = "Mary WriteLine"
aryText(1) = "Had"
aryText(2) = "Another"
aryText(3) = "Little"
aryText(4) = "One"
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)

For i = 0 To 4
objWriter.WriteLine(aryText(i))
Next

objWriter.Close()
MsgBox("Text Appended to the File")
The lines that have changed are in bold, red. But as you can see, not much has changed! But try both version and see how they work.

Creating a file if it doesn't exist

If you want to create a file if one doesn't exist, the process is again quite simple:
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, False)
This time, we've just added the word "False" to the end of FILE_NAME. This will ensure that a new text file is created if one doesn't exist.

0 comments:

Search Here