Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

322 Part II Programming Fundamentals


My.Computer.FileSystem.WriteAllText( _
SaveFileDialog1.FileName, txtNote.Text, False)
End If

WriteAllText takes three parameters. The first parameter specifies the file (in this case, the
user specifies the file using SaveFileDialog1). The second parameter specifies the text to write
to the file (in this case, the contents of the txtNote text box). The last parameter specifies
whether to append the text or overwrite the existing text. A value of False for the last
parameter directs Visual Basic to overwrite the existing text.

The StreamWriter Class


Similar to its companion, the StreamReader class, the StreamWriter class in the .NET
Framework library allows you to write text to files in your programs. To make it easier to use
the StreamWriter class, you add the following Imports statement to the top of your code:

Imports System.IO

Then, if your program contains a text box object, you can write the contents to a file by
using the following program code. (The text file in this example is Output .txt, and the code
assumes an object named TextBox1 has been created on your form .)

Dim StreamToWrite As StreamWriter
StreamToWrite = New StreamWriter("C:\vb10sbs\chap13\output.txt")
StreamToWrite.Write(TextBox1.Text)
StreamToWrite.Close()

In this StreamWriter example, I declare a variable named StreamToWrite of the type
StreamWriter, and then I specify a valid path for the file I want to write to. Next, I write the
contents of the text box to the file by using the Write method. The final statement closes the
StreamWriter. Closing the StreamWriter can be important because if you try to read or write
to the file again, you might get an exception that indicates the process cannot access the file.

You can also use a combination of the My namespace and the StreamWriter class. The
following example writes to a text file line by line. The OpenTextFileWriter method in the My
namespace opens a StreamWriter. The WriteLine method writes one line to the file. When you
are finished with a StreamWriter, you should close it by calling the Close method.

Dim LineOfText As String = ""
Dim StreamToWrite As StreamWriter
StreamToWrite = My.Computer.FileSystem.OpenTextFileWriter( _
"C:\vb10sbs\chap13\output.txt", False)
'get line of text
LineOfText = InputBox("Enter line")
Do Until LineOfText = ""
'write line to file
StreamToWrite.WriteLine(LineOfText)
Free download pdf