JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Writing Text with the StreamWriter Class

As discussed in the In Depth section of this chapter, you can use the StreamWriter class to write text to a file. In the topic "Opening or Creating a File with the FileStream Class" in this chapter, I used a FileStream object to create a file for writing in the StreamWriterReader example on the CD-ROM. In this topic, I can continue that example by using that FileStream object to create a StreamWriter object and use StreamWriter methods to write sample text to the file. Here's how this looks (note that I've discussed these methods in the In Depth section of this chapter; for example, Write just writes text, while WriteLine follows the text it writes with a carriage-return/linefeed pair):

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()
        
    End Sub
End Class
Tip 

I'm using the Flush method here—as mentioned in the In Depth section of this chapter—because file handling is buffered in Visual Basic, nothing is written to disk until the buffer is flushed. This happens automatically when the buffer is full or when you close a file (or when the associated stream object goes out of scope) so you don't have to use Flush, but you can use the Flush method to explicitly flush data to the disk. I'm using it here just to show that it exists.

At the end of this code, I close the file, which makes it available to other programs. We also can open the file again and read the text data back in, using the StreamReader class. I'll do that in the next two topics.

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor