C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
In Main: The StreamWriter is instantiated and the file "myfile.txt" is opened for writing. You can change the path to another location if needed.
Next: The Write call and the two WriteLine calls write the three Strings to the file. The file's contents are listed in the comment.
VB.NET program that uses StreamWriter
Imports System.IO
Module Module1
Sub Main()
Using writer As StreamWriter =
New StreamWriter("myfile.txt")
writer.Write("One ")
writer.WriteLine("two 2")
writer.WriteLine("Three")
End Using
End Sub
End Module
Output file
One two 2
Three
Info: The first part of the example opens the file at the absolute path "C:\append.txt".
Append: The second argument to the StreamWriter constructor is the Boolean True. This specifies the append overload.
BooleanThen: The file is opened again, and a second line is appended to it. The text file contents are shown in the final comment.
VB.NET program that uses StreamWriter to append
Imports System.IO
Module Module1
Sub Main()
' Append the first line of text to a new file.
Using writer As StreamWriter =
New StreamWriter("C:\append.txt", True)
writer.WriteLine("First line appended; 1")
End Using
' Append the second line.
Using writer As StreamWriter =
New StreamWriter("C:\append.txt", True)
writer.WriteLine("Second line appended; 2")
End Using
End Sub
End Module
Output file
First line appended; 1
Second line appended; 2
Write: The file is opened, and one Windows file handle is created. Then, that same system resource is used to write ten numbers to the file.
Format: The Write call in the For-loop specifies a format string. The format string prints the Integer with one decimal place.
IntegerVB.NET program that uses For-loop, StreamWriter
Imports System.IO
Module Module1
Sub Main()
' Create new file.
Using writer As StreamWriter =
New StreamWriter("loop.txt")
' Loop through ten numbers.
Dim i As Integer
For i = 0 To 10 - 1
' Write number with format string.
writer.Write("{0:0.0} ", i)
Next i
End Using
End Sub
End Module
Output file
0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
Tip: If you are not employing the Using construct in VB.NET, make sure to always call Close and Dispose.
Note: The Using statement is implemented with Finally logic. This ensures cleanup always occurs.