5.7. Read and Write a Text File

Problem

You need to write data to a sequential text file using ASCII, Unicode (UTF-16), or UTF-8 encoding.

Solution

Create a new System.IO.FileStream object that references the file. To write the file, wrap the FileStream in a System.IO.StreamWriter and use the overloaded Write method. To read the file, wrap the FileStream in a System.IO.StreamReader and use the Read or ReadLine method. The File class also provides the Shared CreateText and OpenText methods for writing and reading UTF-8 files. Another alternative is to use the OpenTextFileReader and OpenTextFileWriter methods of the My.Computer.FileSystem class. These methods open a file and return a StreamReader or StreamWriter, respectively.

How It Works

The ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.