In the topic "Writing Text with the StreamWriter Class" in this chapter, I used the StreamWriter class to write text to a file in the StreamWriterReader example on the CD-ROM. You also can use the StreamReader class to read that text back in, and I do that in the StreamWriterReader example like this, as discussed in the In Depth section of this chapter:
Imports System Imports System.IO Public Class Form1 Inherits System.Windows.Forms.Form 'Windows Form Designer generated code Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim fs As New System.IO.FileStream("file.txt", FileMode.Create, _ FileAccess.Write) Dim w As New StreamWriter(fs) w.BaseStream.Seek(0, SeekOrigin.End) w.WriteLine("Here is the file's text.") w.Write("Here is more file text." & ControlChars.CrLf) w.WriteLine("And that's about it.") w.Flush() w.Close() fs = New System.IO.FileStream("file.txt", FileMode.Open, _ FileAccess.Read) Dim r As New StreamReader(fs) r.BaseStream.Seek(0, SeekOrigin.Begin) While r.Peek() > -1 TextBox1.Text &= r.ReadLine() & ControlChars.CrLf End While r.Close() End Sub End Class
This code reads the text we've written to the file file.txt and displays it in a text box, as you see in Figure 13.3. As discussed in the In Depth section of this chapter, you use StreamWriter and StreamReader with text—if you want to handle binary data, use BinaryWriter and BinaryReader (see the next few topics).