VB.NET Using StreamWriter

by Sam Allen - Updated January 30, 2010

You have text data you need to write to a file in VB.NET. StreamWriter is an excellent class for this purpose, but you want to see some examples first. Here we see several examples on how you can effectively use StreamWriter in the VB.NET language.

Using StreamWriter to write file

Here we see how you can use StreamWriter to create a new file, and then write two lines of text to it along with two newlines. Note how the System.IO namespace must be imported at the top.

--- Module that uses StreamWriter (VB.NET) ---

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 contents ---

One two 2
Three

Explanation of the code. In the Main entry point, the StreamWriter is instantiated and the file "myfile.txt" is opened for writing. This file is located in the same directory as the application.

Write calls. The Write call and the two WriteLine calls write the three Strings to the file. The file's contents are listed in the comment.

Appending text

Here we see how you can use StreamWriter to append lines of text to a file. This is more efficient than reading in the entire file each time, as only the last part of the file needs to be accessed.

--- Module that uses StreamWriter to append (VB.NET) ---

Imports System.IO

Module Module1
    Sub Main()
        ' 1: 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

        ' 2: 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 contents ---

First line appended; 1
Second line appended; 2

Example part 1. The first part of the example opens the file at the absolute path "C:\append.txt". The second argument to the StreamWriter constructor is True, which specifies the append overload.

Example part 2. The file is then opened again, and a second line is appended to it. The text file contents are shown in the final comment. Try this: run the program again, and the file will contain 4 lines.

Using StreamWriter For loop

Here we see how you can use a For loop inside of a StreamWriter statement. When you have to loop and add text to a file, you should avoid creating many file handles and simply use the same one, as shown here.

--- Module that uses For loop and StreamWriter (VB.NET) ---

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

--- Contents of output file ---

0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

Explanation of example. 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 string. The Write call in the For loop specifies a format string. The format string prints the Integer with one decimal place. All the numbers are written to the same line.

Encodings note

You need to specify the encoding of your target file in the StreamWriter constructor if it is not the default UTF8. Internally, StreamWriter specifies UTF8 by default. The encoding you use depends on what language your program needs.

Extra Functions

StreamWriter in VB.NET has a few more functions on it, but most of them are not often needed. For example, the Close and Dispose calls are occasionally useful, but not if you use the Using statement.

When to use Close and Dispose. If you are not employing the Using construct in VB.NET, make sure to always call Close and Dispose. The Using statement is implemented with Finally logic.

Summary

Here we saw several examples of using StreamWriter in VB.NET. This is one of the easiest ways to write to files in the .NET platform. Refer to the documents at this site for StreamReader if you need to read files.

(See Using StreamReader Examples.)

(See File Handling.)

(Do not copy this page.)

Dot Net Perls | Search
VB.NET | DataGridView Usage | Dictionary Tips and Examples | Split String Examples | StringBuilder Examples | Using StreamReader Examples
C# | Obsolete Attribute | True and False | Gradient Tips | Catch Examples
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen