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

594 Chapter 13 WORKING WITH FOLDERS AND FILES

Console.WriteLine(“

LENGTH

“ & FI.Length.ToString)

Console.WriteLine(“

EXTENSION

“ & FI.Extension)

Console.WriteLine(“

CREATED

“ & FI.CreationTime)

Console.WriteLine(“

ACCESSED

“ & FI.LastAccessTime.ToShortDateString)

If FI.Attributes = FileAttributes.Normal > 0 Then Console.Write(“ NORMAL FILE “)

Exit Sub End If

Console.Write(“ ATTRIBUTES “)

If FI.Attributes And FileAttributes.Archive Then Console.Write(“Archive “) If FI.Attributes And FileAttributes.Compressed Then _

Console.Write(“Compressed “)

If FI.Attributes And FileAttributes.Directory Then _ Console.Write(“Directory “)

If FI.Attributes And FileAttributes.Encrypted Then _ Console.Write(“Encrypted “)

If FI.Attributes And FileAttributes.Hidden Then Console.Write(“Hidden “) If FI.Attributes And FileAttributes.NotContentIndexed Then _

Console.Write(“Not Indexed “)

If FI.Attributes And FileAttributes.Offline Then Console.Write(“OffLine “) If FI.Attributes And FileAttributes.ReadOnly Then Console.Write(“ReadOnly “) If FI.Attributes And FileAttributes.System Then Console.Write(“System “)

If FI.Attributes And FileAttributes.Temporary Then _ Console.Write(“Temp File “)

Console.WriteLine() End Sub

When you select a file in the FileList control, a few lines like the following will be printed in the Output window:

desktop.ini

 

LENGTH

271

EXTENSION

.ini

CREATED

6/9/2000 2:51:24 PM

ACCESSED

03/17/2001

ATTRIBUTES Hidden

Notice that all files are displayed in the FilesList control, because the Directory.GetFiles method returns by default all the files (see Listing 13.12). If you want to hide certain types of files, you must insert the appropriate code in the ShowFilesInFolder() subroutine.

Accessing Files

In the first half of the chapter, you learned how to manipulate files and folders. Now we’re going to discuss how to access files (read from or write into them). There are two types of files, text files and binary files. Of course, you can classify files in any way you like, but when it comes to writing to and

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FILES 595

reading from files, it’s convenient to treat them either as text or binary. A binary file is any file that doesn’t contains plain text. Text files are usually read by line, or in their entirety into a String variable. Binary files must be read according to the type of the information stored in them. A bitmap file, for instance, must be read one byte at a time. Each pixel is usually represented by three or four bytes, and you must combine the values read to reconstruct the pixel’s color. Or you can read a Color variable at a time. A binary file that contains doubles must be read one double at a time. Most binary files contain multiple data types, and you must know the organization of a file before you can read it. A Double value is stored in 8 bytes, and an Integer value is stored in 4 bytes. Unless you know how to read a binary file, you won’t get the correct values out of it.

So the division of files into text and binary is dictated by our need to store data in them or get data out of them. In the following sections, you’ll see that the .NET Framework provides different objects and different methods for manipulating text and binary files. It is possible to read text files as binary files, one byte at a time, but then you must reconstruct the original characters. It is also possible to store text into binary files and embed into it binary data types like integers, doubles, and dates.

Practically, you can distinguish text from binary files by the fact that text files can be read. Binary files contain mostly unprintable characters, and even the numeric digits in them don’t make much sense. You can read any strings that may be part of the file, but an integer number isn’t stored as text. Binary files can’t be read with a text editor.

To access a file, you must first set up a Stream object. Stream objects are created by the various methods that open or create a file, as you have seen in the previous sections, and they return information about the file they’re connected to. Once the Stream object is in place, you create a Reader or Writer object, which enables you to read information from or write information into the Stream. There are two types of Reader objects: the StreamReader for text files and the BinaryReader for binary files. Likewise, there are two Writer objects, the StreamWriter and the BinaryWriter. These objects expose a few properties and methods for writing to files and reading from them, and these members are discussed shortly.

Previous versions of Visual Basic supported statements for accessing the so-called random-access files. A random-access file contains records (structures) of fixed length, and you can quickly access any record in the file. Although you can still use random access with VB.NET, it’s not recommended that you write applications based on random-access files. To support this type of application, you need a database. I’m not going to discuss random-access files in this chapter, because they’re already obsolete. Remember that the Serializer object can save an array of custom structures to disk and load them back into the array. For small sets of data, use arrays of structures (or any of the Collections discussed in Chapter 11), and for larger data sets, deploy a database.

The FileStream Object

The StreamReader/StreamWriter and BinaryReader/BinaryWriter objects allow you to read from or write to text and binary files through a FileStream object. To prepare your application to write to a text file, you must set up a FileStream object, which is the channel between your application and the file. There are many ways to set up a FileStream object and associate it with a file, and they’re described in the following sections. All the objects are contained in the System.IO namespace, so don’t forget to import the System.IO namespace in your projects that perform file input/output. It’s the same namespace that exposes the Directory, File, Path, and other classes discussed so far.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

596 Chapter 13 WORKING WITH FOLDERS AND FILES

The FileStream object exposes a few members, that convey information about the file you’re accessing through a FileStream variable. We’ll cover these members here, and then we’ll discuss the Reader and Writer objects that actually write data to or read it from files.

The FileStream object’s constructor is overloaded; its most common forms require that you specify the path of the file and the mode in which the file will be opened (for reading, appending, writing, and so on). The simpler form of the constructor is

Dim FS As New FileStream(path, fileMode)

The fileMode argument is a member of the FileMode enumeration (see Table 13.3). It’s the same argument used by the Open method of the File class. Also similar to Open method of the File class, another overloaded form of the constructor allows you to specify the file’s access mode, and the syntax of this method is

Dim FS As New FileStream(path, fileMode, fileAccess)

The last argument is a member of the FileAccess enumeration (see Table 13.4). The last overloaded form of the constructor accepts a fourth argument, which determines the file’s sharing mode:

Dim FS As New FileStream(path, fileMode, fileAccess, fileShare)

The fileShare argument’s value is a member of the FileShare enumeration (see Table 13.5).

Properties

You can use the following properties of the FileStream object to retrieve information about the underlying file.

CanRead

This read-only property determines whether the current stream supports reading. If the file associated with a specific FileStream object can be read, this property returns True.

CanSeek

This read-only property determines whether the current stream supports seeking. A seek operation in the context of files doesn’t locate a specific value in the file. It simply moves the current position to any location within the file.

CanWrite

This read-only value determines whether the current stream supports writing. If the file associated with a specific FileStream object can be written to, this property returns True.

Length

This read-only property returns the length of the file associated with the FileStream in bytes.

Position

This property gets or sets the current position within the stream. You can compare the Position property to the Length property to find out whether you have reach the end of an existing file. When these two properties are equal, there are no more data to read.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FILES 597

Methods

The FileStream object exposes the following methods that support input/output operations. The methods for accessing a file’s contents are discussed in the following section (you can’t access the file’s contents with a FileStream object).

Lock

This method allows you to lock the file you’re accessing, or part of it. The syntax of the Lock method is

Lock(position, length)

where position is the starting position and length is the length of the range to be locked. To lock the entire file, use the statement

FileStream.Lock(1, FileStream.Length)

Seek

This method sets the current position in the file represented by the FileStream object:

FileStream.Seek(offset, origin)

The new position is offset bytes from the origin. In the place of the origin argument, use one of the SeekOrigin enumeration members, listed in Table 13.6.

Table 13.6: The SeekOrigin Enumeration

Value

Effect

Begin

The offset is relative to the beginning of the file.

Current

The offset is relative to the current position in the file.

End

The offset is relative to the end of the file.

 

 

SetLength

This method sets the length of the file represented by the FileStream object. Use this method after you have written to an existing file, to truncate its length. The syntax of the SetLength method is

FileStream.SetLength(newLength)

If the specified value is less than the length of the file, the file is truncated. Otherwise, the file is expanded. The bytes after the length of the original file all the way to the end of the new file are undefined.

The StreamWriter Object

The StreamWriter object is the channel through which you send data to the text file. To create a new StreamWriter object, declare a variable of the StreamWriter type. The constructor of the StreamWriter

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

598 Chapter 13 WORKING WITH FOLDERS AND FILES

object is overloaded, and its various forms are discussed next. The first form creates a new StreamWriter object for a file:

Dim SW As New StreamWriter(path)

This form of the constructor creates a new StreamWriter object for the file specified by the path argument. The new object has the default encoding and the default buffer size. The encoding scheme determines how characters are saved (the default encoding is UTF-8), and the buffer size determines the size of a buffer where data are stored before they’re sent to the file. The following statement creates a new StreamWriter object and associates it with the specified file:

Dim SW As New StreamWriter(“c:\TextFile.txt”)

Another form of the same constructor creates a new StreamWriter object for the specified file using the default encoding and buffer size, but it allows you to overwrite existing files. If the overwrite argument is True, you can overwrite the contents of an existing file.

Dim SW As New StreamWriter(path, overwrite)

You can also specify the encoding for the StreamWriter with the following form of the constructor:

Dim SW As New StreamWriter(path, overwrite, encoding)

The last form of the constructor that accepts a file’s path allows you to specify both the encoding and the buffer size:

Dim SW As New StreamWriter(path, overwrite, encoding, bufferSize)

The same forms of the constructor can be used with a FileStream object. The simplest form of this type of constructor is

Dim SW As New StreamWriter(stream)

This form creates a new StreamWriter object for the FileStream specified by the stream argument. To use this form of the constructor, you must first create a new FileStream object and then use it to instantiate a StreamWriter object:

Dim FS As FileStream

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

Dim SW As StreamWriter

SW = New StreamWriter(FS)

Finally, there are two more forms of the StreamWriter constructor that accept a FileStream object as the first argument. These forms are simply listed here:

New StreamWriter(stream, encoding)

New StreamWriter(stream, encoding, bufferSize)

Once you have created the StreamWriter object, you can call its members to manipulate the underlying file. These are described in the following sections.

Property: NewLine

The StreamWriter object provides a very handy property, the NewLine property, which allows you to change the string used to terminate each line in the file. This terminator is written to the text file

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FILES 599

by the WriteLine method, following the text. The default line-terminator string is a carriage return followed by a line feed (“\r\n”).

Note The TextReader object doesn’t provide a similar property. It reads lines terminated by the carriage return (\r), line feed (\n) or carriage return/line feed (\r\n) characters only.

Methods

To send information to the underlying file, use the following methods of the StreamWriter object.

AutoFlush

This property is a True/False value that determines whether the methods that write to the file (the Write and WriteString methods) will also flush their buffer. If you set this property to False, then the buffer will be flushed when the operating system gets a chance, when the Flush method is called, or when you close the FileStream object. The False setting may help your application’s performance, but only for very large files. When AutoFlush is True, then the buffer is flushed with every write operation.

Close

This method closes the StreamWriter object and releases the resources associated with it to the system. Always call the Close method after you’re done using the StreamWriter object. If you have created the StreamWriter object on a FileStream object, you must also close the underlying stream.

Flush

This method clears writes any data in the buffer to the underlying file.

Write(data)

This method writes the data specified by the data argument to the stream on which it’s applied. The Write method is overloaded and can accept any data type as argument. When you pass a numeric value as argument, the Write method stores it to the file as a string. This is the same string as you’d get with the number’s ToString method. You can write any data type to the file, except for the Date type. To save dates to a text file, you must convert them to strings with one of the methods of the Date data type. You can even write objects to the file, and you will see shortly how the Write method handles objects.

There’s one form of the Write method I would like to discuss here, and this is similar to the Console.WriteLine method, which accepts a string with embedded format arguments, followed by a list of values, one for each argument. The following statement writes a string with two embedded numeric values in it:

SW.Write(“Your price is ${0} plus ${1} for shipping”, 86.50, 12.99)

This statement will write the following string to the file:

Your price is $86.50 plus $12.99 for shipping

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com