Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

600 Chapter 13 WORKING WITH FOLDERS AND FILES

WriteLine(data)

This method is identical to the Write method, but it appends a line break after saving the data to the file (the same as the methods of the Console object by the same name).

You will find examples on using the StreamWriter object after we discuss the methods of the StreamReader object.

The StreamReader Object

The StreamReader object provides the necessary methods for reading from a text file. It exposes methods that match those of the StreamWriter object, methods that can read the information written to the file through the StreamWriter’s Write and WriteLine methods.

The StreamReader object’s constructor is overloaded. You can specify the FileStream object it will use to write data to the file, the encoding scheme, and the buffer size. The simplest form of the constructor is

Dim SR As New StreamReader(FS)

This declaration associates the SR variable with the file on which the FS FileStream object was created. This is the most common form of the StreamReader object’s constructor. To prepare your application for reading the contents of the file C:\My Documents\Meeting.txt, use the following statements:

Dim FS As FileStream

Dim SR As StreamReader

FS = New FileStream(“c:\My Documents\Meeting.txt”, _

System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)

SR = New StreamReader(FS)

You can also create a new StreamReader object directly on a file, with the following form of the constructor:

Dim SR As New StreamReader(path)

To create a StreamReader object and associate it with the file of the previous example, use the statement

Dim SR As New StreamReader(“c:\My Documents\Meeting.txt”)

With both forms of the constructor, you can specify the character encoding with a second argument:

Dim SR As New StreamReader(FS, encoding)

Dim SR As New StreamReader(path, encoding)

You can also specify a third argument with the size of the buffer to be used with the file input/output operations:

Dim SR As New StreamReader(FS, encoding, bufferSize)

Dim SR As New StreamReader(path, encoding, bufferSize)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FILES 601

Methods

Close

This method closes the current instance of StreamReader and releases any system resources associated with the StreamReader.

Peek

This method returns the next character without actually removing it from the input stream. The Peek method doesn’t reposition the current position in the stream. If there are no more characters left in the stream, the value –1 is returned. The Peek method will also return –1 if the current stream doesn’t allow peeking.

Read

This method reads a number of characters from the StreamReader object to which it’s applied and returns the number of characters read. This value is usually the same as the number of characters you specified, unless there aren’t as many characters in the file. If you have reached the end of the stream (which is the end of the file), the method returns the value –1. The syntax of the Read method is

charsRead = Read(chars, startIndex, count)

where count is the number of characters to be read. The characters are stored in the chars array of characters, starting at the index specified by the second argument. The return value is the number of characters actually read from the file.

A simpler form of the Read method reads the next character from the stream and returns it as an integer value:

Dim newChar As Integer newChar = SR.Read()

where SR is a properly declared StreamReader object.

ReadBlock

This method reads a number of characters from a text file and stores them in a Character array. It accepts the same arguments as the Read method and returns the number of characters read:

charsRead = SR.Read(chars, startIndex, count)

ReadLine

This method reads the next line from the text file associated with the StreamReader object and returns a string. If you’re at the end of the file, the method returns the Null value. The syntax of the ReadLine method is

Dim txtLine As String txtLine = SR.ReadLine()

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

602 Chapter 13 WORKING WITH FOLDERS AND FILES

A text line is a sequence of characters followed by carriage return (\r), or line feed (\n), or carriage return and line feed (\r\n). Notice that the NewLine character you may have specified for the specific file with the StreamWriter object is ignored by the ReadLine method. The string returned by the method doesn’t include the line terminator.

ReadToEnd

The last method for reading characters from a text file reads all the characters from the current position to the end of the file. We usually call this method once to read the entire file with a single statement and store its contents to a string variable. The syntax of the ReadToEnd method is

allText = SR.ReadToEnd()

Sending Data to a File

The statements in Listing 13.14 demonstrate how to send various data types to a file. You can place the statements of this listing to button’s Click event handler and then open the file with Notepad to see its contents. Everything is in text format, including the numeric values. Don’t forget to import the System.IO namespace to your project.

Listing 13.14: Writing Data to a Text File

Dim SW As StreamWriter

Dim FS As FileStream

FS = New FileStream(“C:\TextData.txt”, FileMode.Create)

SW = New StreamWriter(FS)

SW.WriteLine(9.009)

SW.WriteLine(1 / 3)

SW.Write(“The current date is “)

SW.Write(Now())

SW.WriteLine()

SW.WriteLine(True)

SW.WriteLine(New Rectangle(1, 1, 100, 200))

SW.WriteLine(Color.YellowGreen)

SW.Close()

FS.Close()

Here’s the output produced by Listing 13.14:

9.009

0.333333333333333

The current date is 2001-03-16T12:14:02 True

{X=1,Y=1,Width=100,Height=200} Color [YellowGreen]

Notice how the WriteLine method without an argument inserts a new line character in the file. The statement SW.Write(now()) prints the current date but doesn’t switch to another line. The

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FILES 603

WriteLine method without any arguments starts a new line. The following statements demonstrate a more complicated use of the Write method with formatting arguments:

Dim BDate As Date = #2/8/1960 1:04:00 PM#

SW.WriteLine(“Your age in years is {0}, in months is {1}, “ & _ “in days is {2}, and in hours is {3}.”, _ DateDiff(DateInterval.year, BDate, Now), _ DateDiff(DateInterval.month, BDate, Now), _ DateDiff(DateInterval.day, BDate, Now), _ DateDiff(DateInterval.hour, BDate, Now))

The SW StreamWriter must be declared with the statements at the beginning of Listing 13.14. The day I tested these statements, the following string was written to the file:

Your age in years is 41, in months is 493, in days is 15012.027722980833, and in hours is 360288.66535154.

Of course, the data to be stored to a text file need not be hard-coded in your application. The code of Listing 13.15 stores the contents of a TextBox control to a text file.

Listing 13.15: Storing the Contents of a TextBox Control to a Text File

Dim SW As StreamWriter

Dim FS As FileStream

FS = New FileStream(“C:\TextData.txt”, FileMode.Create)

SW = New StreamWriter(FS)

SW.Write(TextBox1.Text)

To save the contents of a ListBox control to a text file, iterate through its Items collection and store each item to the file. The items of the control will be stored in the file as strings. Neither the StreamWriter nor the BinaryWriter provides a method for storing objects to or reading objects from a file. If you want to store objects, see the discussion of serializing collections in Chapter 11.

The following statements populate a ListBox control with various items:

ListBox1.Items.Add(“First Item”)

ListBox1.Items.Add(New Rectangle(0, 0, 3, 3))

ListBox1.Items.Add(New Point(3.2, 4.01))

ListBox1.Items.Add(“Last Item”)

The code that saves each item to a separate line in the C:\Items.txt file is shown in Listing 13.16.

Listing 13.16: Saving an Items Collection to a Text File

Dim SW As StreamWriter

Dim FS As FileStream

FS = New FileStream(“C:\Items.txt”, FileMode.Create)

SW = New StreamWriter(FS)

Dim itm As Object

For Each itm In ListBox1.Items

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com