JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Reading Text with the StreamReader Class

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, _

        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.")
        fs = New System.IO.FileStream("file.txt", FileMode.Open, _

        Dim r As New StreamReader(fs)
        r.BaseStream.Seek(0, SeekOrigin.Begin)
        While r.Peek() > -1
            TextBox1.Text &= r.ReadLine() & ControlChars.CrLf
        End While
    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).

Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor