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

578 Chapter 13 WORKING WITH FOLDERS AND FILES

where source is the name of the folder to be moved and destination is the name of the destination folder. The Move method doesn’t work along different volumes, and the destination can’t be the same as the source argument, obviously.

Notice the lack of a Copy method that would copy an entire folder to a different location. To copy a folder, you must manually create an identical folder structure and then copy the corresponding files to the proper subfolders.

The File Class

The File class exposes methods for manipulating files (copying, moving them around, opening and closing them), similar to the methods of the Directory class. The names of the methods are selfdescriptive, and most of them accept as argument the path of the file on which they act. Use these methods to implement the common operations users normally perform through the Windows interface from within your application.

Methods

Many of the methods listed in the following sections allow you to open existing or create new files. We’ll use some of these methods later in the chapter to write data to, and read from, text and binary files.

AppendText

This method prepares an existing text file for appending text to it and returns a StreamWriter object. If the file doesn’t exist, it creates a new one and opens it. The syntax of the AppendText method is

FStream = File.AppendText(path)

Copy

This method copies an existing file to a new location; its syntax is

File.Copy(source, destination)

where source is the path of the file to be copied and destination is the path where the file will be copied to. If the destination file exists, the Copy method will fail.

To overwrite the destination file, use the following form of the method, which allows you to specify whether the destination file can be overwritten.

File.Copy(source, destination, overwrite)

If the last argument is True, the destination file is overwritten (if it exists).

The Copy method works across volumes. The following statement copies the file faces.jpg from

the folder c:\My Documents\Screen\ to the folder d:\Fun Images and changes its name to Bouncing

Face.jpg. Notice that both the source and destination paths must already exist. If not, an exception will be thrown.

File.Copy(“c:\My Documents\Screen\faces.jpg”, _

“d:\Fun Images\Bouncing Face.jpg”)

Note The Copy method doesn’t accept wildcard characters. In other words, you can’t copy multiple files with a single call to the Copy method.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FOLDERS AND FILES 579

Create

This method creates a new file and returns a Stream object to this file. You can use this object to write to or read from the file. The Stream object is discussed in detail later in this chapter, along with the methods for writing to or reading from the file. The simplest form of the Create method accepts a single argument, which is the path of the file you want to create:

FStream = File.Create(path)

You can also create a new file and specify the size of the buffer to be associated with this file, with the following form of the method:

FStream = File.Create(path, bufferSize)

where bufferSize is an Integer (Int32) value.

If the specified file exists already, it’s replaced. The new file is opened for read-write operations, and it’s opened exclusively by your application. Other applications can access it only after your application closes it. Once the file has been created, you can use the methods of the Stream object to write to it. These methods are discussed in the section “Accessing Files,” later in this chapter.

There are several exceptions the Create method can raise, which are described in Table 13.1.

Table 13.1: Exceptions of the Create Method

Exception

Description

IOException

The folder you specified doesn’t exist.

ArgumentNullException

The path you specified doesn’t reference a file.

SecurityException

The user of your application doesn’t have permission to create a new file

 

in the specified folder.

ArgumentException

The path you specified is invalid.

AccessException

The file can’t be opened in read-write mode. Most likely, you’ve

 

attempted to open a read-only file, but the File.Create method opens

 

a file in read-write mode.

DirectoryNotFoundException

The folder you specified doesn’t exist.

 

 

Note that pathnames are limited to 248 characters, and filenames are limited to 259 characters.

CreateText

This method is similar to the Create method, but it creates a text file and returns a StreamWriter object for writing to the file. The StreamWriter object is similar to the Stream object, but used for text files only, whereas the StreamWriter object can be used with both text and binary files.

The syntax of the CreateText method is

File.CreateText(path)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

580 Chapter 13 WORKING WITH FOLDERS AND FILES

and it returns an object that must be declared as follows:

Dim SW As StreamWriter

SW = File.CreateText(path)

You will learn more about reading from and writing to files later in this chapter.

Delete

This method removes the specified file from the file system. The syntax of the Delete method is

File.Delete(path)

where path is the path of the File object you want to delete. This method will raise an exception if the file is open at the time for reading or writing, or if the file doesn’t exist.

Exists

This property is a True/False value that indicates whether a file exists or not. The following statements delete a file, after making sure that the file exists already:

If File.Exists(path) Then

File.Delete(path)

Else

MsgBox(“The file “ & path & “ doesn’t exist”)

End If

The Delete method will not raise an exception if the file doesn’t exist, so you don’t have to make sure that a file exists before deleting it. You can use similar statements to confirm that a file exists before attempting to open it.

GetAttributes

This method accepts a file path as argument and returns the attributes of the specified file. The method returns a FileAttributes object, which contains all the attributes. A file may have more than a single attribute (for instance, it can be hidden and compressed). Table 13.2 lists all possible attributes a file can have.

Table 13.2: The Attributes of a File

Value

Description

Archive

The file’s archive status. Most of the files in your file system have the Archive

 

attribute.

Compressed

The file is compressed.

Encrypted

The file is encrypted.

Hidden

The file is hidden, and it doesn’t appear in an ordinary directory listing.

Normal

Normal files have no other attributes, so this setting excludes all other attributes.

 

Continued on next page

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

 

ACCESSING FOLDERS AND FILES

581

 

 

 

 

 

 

Table 13.2: The Attributes of a File (continued)

 

 

Value

Description

NotContentIndexed

The file isn’t indexed by the operating system’s content indexing service.

Offline

The file is offline and its contents may not be available at all times.

ReadOnly

The file is read-only.

SparseFile

The file is sparse (a large files whose data are mostly zeros).

System

A system file is part of the operating system or is used exclusively by the operating

 

system.

Temporary

The file is temporary. Temporary files are created by applications and they’re

 

deleted by the same applications that created them when they terminate.

 

 

 

 

To examine whether a file has an attribute set, you must AND the value returned by the GetAttributes methods with the desired attribute, which is a member of the FileAttributes enumeration. To find out whether a file is read-only, use the following If statement:

If File.GetAttributes(fpath) And FileAttributes.ReadOnly Then

Console.WriteLine(“The file “ & fpath & “ is read only”)

Else

Console.WriteLine(“You can write to the file “ & fpath)

End If

You can also retrieve a file’s attributes through the FileInfo object, described later in this chapter.

GetCreationTime, SetCreationTime

The GetCreationTime method returns a date value, which is the date and time the file was created. This value is set by the operating system, but you can change it with the SetCreationTime method. The following statement returns a value like the one shown in bold underneath it:

Console.WriteLine(File.GetCreationTime(“c:\config.sys”))

6/13/2001 1:27:48 PM

The SetCreationTime allows you to change the file’s creation time; it accepts as argument the file’s path and the new creation time:

File.SetCreationTime(path, datetime)

GetLastAccessTime, SetLastAccessTime

The GetLastAccessTime method returns a date value, which is the date and time the specified file was accessed for the last time. Use the SetLastAccessTime method to set this value. SetLastAccessTime accepts as arguments the file whose last access time you want to set and the desired date. Changing the last access of a file is sometimes called “touching” the file. If you have a utility that manipulates files according to when they were last used (for example, one that moves data files that haven’t been accessed in the last three months to tape), you can “touch” a few files to exclude them from the operation.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

582 Chapter 13 WORKING WITH FOLDERS AND FILES

GetLastWriteTime, SetLastWriteTime

The GetLastWriteTime method returns a date value, which is the date and time the specified file was written to for the last time. You can set this value with the SetLastWriteTime method.

Move

This method moves the specified file to a new location. You can also use the Move method to rename a file, by simply moving it to another name in the same folder. Moving a file is equivalent to copying it to another location and then deleting the original file. The Move method works across volumes.

File.Move(sourceFileName, destFileName)

The first argument is the path of the file to be moved, and the second argument is the path of the destination file. The following statement move the file Boston Trip.xls from the folder C:\My

Document\Business to the folder \\Accounts\Expenses\JamesK\:

File.Move(“C:\My Document\Business\Boston Trip.xls”, _

“\\Accounts\Expenses\JamesK\Boston Trip.xls”)

Open

This method opens an existing file for read-write operations. The simplest form of the method is

FStream = File.Open(path)

which opens the file specified by the path argument and returns a Stream object to this file. The following form of the method allows you to specify the mode in which you want to open the file:

FStream = fileObj.Open(path, fileMode)

where the fileMode argument can have one of the values shown in Table 13.3.

Table 13.3: The FileMode Enumeration

Value

Effect

Append

Opens the file in write mode, and all the data you write to the file are appended to its exist-

 

ing contents.

Create

Requests the creation of a new file. If a file by the same name exists, this will be overwritten.

CreateNew

Requests the creation of a new file. If a file by the same name exists, an exception will be

 

thrown. This mode will create and open a file only if it doesn’t already exist.

Open

Requests that an existing file be opened.

OpenOrCreate

Opens the file in read-write mode if the file exists, or creates a new file and opens it in read-

 

write mode if the file doesn’t exist.

Truncate

Opens an existing file and resets its size to zero bytes. As you can guess, this file must be

 

opened in write mode.

 

 

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FOLDERS AND FILES 583

Another form of the Open method allows you to specify the access mode, in addition to the file mode:

FStream = File.Open(path, fileMode, accessMode)

where the accessMode argument can have one of the values listed in Table 13.4.

Table 13.4: The FileAccess Enumeration

Value

Effect

Read

The file is opened in read-only mode. You can read from the Stream object that is returned,

 

but an exception will be thrown if you attempt to write to the file.

ReadWrite

The file opened in read-write mode. You can either write to the file or read from it.

Write

The file is opened in write mode. You can write to the file, but if you attempt to read from

 

it, an exception will be thrown.

 

 

You can also specify a fourth argument to the Open method, which specifies how the file will be shared with other applications. This form of the method requires that the other two arguments (fileMode and accessMode) be supplied as well:

FStream = File.Open(path, fileMode, accessMode, shareMode)

The shareMode argument determines how the file will be shared among multiple applications and can have one of the values from Table 13.5.

Table 13.5: The FileShare Enumeration

Value

Effect

None

The file can’t be shared for reading or writing. If another application attempts to open the

 

file, it will fail until the current application closes the file.

Read

The file can be opened by other applications for reading, but not for writing.

ReadWrite

The file can be opened by other applications for reading or writing.

Write

The file can be opened by other applications for writing, but not for reading.

 

 

OpenRead

This method opens an existing file in read mode and returns a stream object associated with this file. You can use this stream to read from the file.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com