- Opening Text Files for Reading
- Reading from an Open Text File
- Opening and Creating Text Files for Writing
- Writing to a Text File
- Summing Up
Opening and Creating Text Files for Writing
Writing data to a text file uses the StreamWriter class. Writing to a file has a few more complexities than reading data, depending on whether the output file already exists. There are three possibilities:
- The file doesn’t exist and needs to be created.
- The file exists and you want to overwrite it with the new data.
- The file exists and you want to append the new data to the existing data in the file.
If you want to create a new file or overwrite any existing file, use the default StreamWriter constructor:
Dim sw As New StreamWriter(filename)
If you want to append text to an existing file, use this constructor:
Dim sw As New StreamWriter(filename, true)
This second constructor will also create a new file if the file doesn’t already exist.
As with files opened for reading, you should close files opened for writing once you’re done with them, using the StreamWriter.Close() method.