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

570 Chapter 13 WORKING WITH FOLDERS AND FILES

Accessing Folders and Files

In this section, you’ll learn how to access and manipulate files and folders with the help of the Directory and File classes. The Directory class provides methods for manipulating folders, and the File class provides methods for manipulating files. These two objects allow you to perform just about any operation you can perform on a folder and a file, respectively, short of storing data into or reading from files.

Tip Directory is another name for folder; they mean the same thing, but folder is the more familiar term in Windows. When it comes to developers and administrators, Microsoft still uses the term directory (the Active Directory, the Directory object, and so on).

Keep in mind that Directory and File objects don’t represent folders or files. The two objects that represent these entities are the DirectoryInfo and FileInfo classes. If you’re in doubt as to which class you should use in your code, consider that the members of the Directory and File classes are shared: you can call them without having to explicitly create an instance of the corresponding object first. The methods of the DirectoryInfo and FileInfo are instance methods: they apply to an instance of the corresponding object.

Both the Directory and the DirectoryInfo classes allow you to delete a folder, including its subfolders. The Delete method of the DirectoryInfo class will act on a directory you specified when you instantiated the DirectoryInfo class:

Dim DI As New DirectoryInfo(“C:\Work Files\Assignments”)

DI.Delete()

But you can’t call Delete on a DirectoryInfo object that you haven’t specifically declared. The DirectoryInfo.Delete method doesn’t accept the name of a folder as argument. In short, you can’t use the DirectoryInfo class without first creating an instance of it, which references a specific folder. The Delete method of the Directory class can be called at any time, by passing as argument the

path of the folder to be deleted:

Directory.Delete(“C:\Work Files\Assignments”)

The two classes expose similar members for performing basic file and folder operations, and it shouldn’t come as a surprise that there’s a substantial overlap between the classes’ methods.

I will start this chapter with a detailed discussion of the Directory and File classes, which are richer, and then I’ll go quickly through the members of the DirectoryInfo and FileInfo classes.

The Directory Class

The Directory class exposes all the members you need to manipulate folders, and you must import it into any project that may require its members with the following statement, which must appear at the beginning of the file, outside any class:

Imports System.IO

Methods

The Directory object exposes methods for accessing folders and their contents, which are described in the following sections.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FOLDERS AND FILES 571

CreateDirectory

This method creates a new folder, whose path is specified by a string passed as argument to the method:

Directory.CreateDirectory(path)

path is the fully qualified path of the folder you want to create and can be either an absolute or a relative path. If it’s a relative path, its absolute value is determined by the current drive and path.

The CreateDirectory method returns a DirectoryInfo object, which contains information about the newly created folder. The DirectoryInfo object is discussed later in this chapter along with the FileInfo object.

Notice that the CreateDirectory method can create multiple nested folders in a single call. The statement

Directory.CreateDirectory(“C:\folder1\folder2\folder3”)

will create the folder folder1 (if it doesn’t exist), then folder2 (if it doesn’t exist) under folder1, and finally folder3 under folder2 in the C: drive. If folder1 exists already, but it doesn’t contain a subfolder named folder2, then folder2 will be automatically created. An exception will also be thrown if the total path is too long, or if your application doesn’t have permission to create a folder in the specified path. However, no exception will be thrown if the specified path exists on the disk already. The method will simply not create any new folders. It will still return a DirectoryInfo object, which describes the existing folder.

Delete

This method deletes a folder and all the files in it. If the folder contains subfolders, the Delete method will optionally remove the entire directory tree under the node you’re removing. The simplest form of the Delete method is

Directory.Delete(path)

where path is the path of the folder to be deleted. This method will delete the specified path only. If the specified folder contains subfolders, they will not be deleted and, therefore, the specified folder won’t be deleted either.

To delete a folder recursively (that is, also delete any subfolders under it), use the second form of the Delete method, which accepts a second argument:

Directory.Delete(path, force)

The force argument is a True/False value that determines whether the Delete method will delete the subfolders under the specified folder or not. If True, the folder will be removed, along with its files and subfolders.

The statements in Listing 13.1 attempt to delete a single folder. If the folder contains subfolders, the Delete method will fail and an exception handler will be activated. The exception handler examines the type of exception, and if it was caused because the folder isn’t empty, it can call the second form of the Delete method forcing it to delete the folder recursively. Create a new project, insert the statement Imports System.IO at the beginning of the file, and then place the statements of Listing 13.1 in a button’s Click event handler to experiment with the code.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

572 Chapter 13 WORKING WITH FOLDERS AND FILES

Listing 13.1: Deleting a Directory

Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click Directory.CreateDirectory(“c:/folder1/folder2/folder3”)

Try

Directory.Delete(“c:\folder1”, False) Catch exc As IOException

If exc.ToString.IndexOf(“The directory is not empty”) >= 0 Then Dim reply As MsgBoxResult

reply = MsgBox(“Delete all files and subfolders?”, _ MsgBoxStyle.YesNo, exc.Message)

If reply = MsgBoxResult.Yes Then Directory.Delete(“c:\folder1”, True)

Else MsgBox(exc.Message)

End If End If

End Try End Sub

Exists

This method accepts a path as argument and returns a True/False value indicating whether the specified folder exists.

Directory.Exists(path)

The Delete method will throw an exception if you attempt to delete a folder that doesn’t exist, so you can use the Exists method to make sure the folder exists, before attempting to delete it:

If Directory.Exists(path) Then Directory.Delete(path)

Of course, the Delete method may fail for other reasons as well, and you should provide an error handler—for example, the Delete method will fail if the folder contains read-only files.

GetCreationTime, SetCreationTime

These methods read or set the date a specific folder was created. The GetCreationTime method accepts a path as argument and returns a Date value:

Dim CreatedOn As Date

CreatedOn = Directory.GetCreationTime(path)

SetCreationTime accepts a path and a date value as argument and sets the specified folder’s creation time to the value specified by the second argument:

Directory.SetCreationTime(path, datetime)

You shouldn’t change the creation dates of files except on rare occasions. If you do, you will never be able to read the file’s original creation date.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FOLDERS AND FILES 573

GetCurrentDirectory, SetCurrentDirectory

Use these methods to retrieve and set the path of the current directory. The current directory is a basic concept when working with the Directory class. We will use this technique in the CustomExplorer project, later in this chapter. The first time you call the GetCurrentDirectory method, it will return the folder in which the application is running. If you set the current folder with the SetCurrentDirectory method, the GetCurrentDirectory method will retrieve the name of the new current folder. The SetCurrentDirectory accepts a string argument, which is a path, and sets the current directory to the specified path.

The expression Directory.GetCurrentDirectory will return the application’s current folder. For the default installation, it’s something like

C:\Documents and Settings\TOOLKIT\My Documents\Visual Studio Projects\

DirectoryFileSamples\bin

(DirectoryFileSamples is the name of the project I used to test the short samples of this chapter.) You can change the current folder with a relative path like the following:

Directory.SetCurrentDirectory(“..\..\..\My Pictures”)

The two periods are a shortcut for the parent folder. From the bin folder just named, this statement moves up three levels to the My Documents folder and then to the My Pictures folder under My Documents (assuming that there is a folder by that name). So this SetCurrentDirectory statement switches the current folder to

C:\Documents and Settings\TOOLKIT\My Documents\My Pictures

Notice that the value you pass to the SetCurrentDirectory method as argument must be the name of an existing folder. If not, a FileNotFound exception will be thrown. You can also switch to a folder on another drive, if you specify the full folder’s path, including its drive letter. To handle possible errors, use the SetCurrentDirectory method with a structured error handler like the one in Listing 13.2.

Listing 13.2: Changing the Current Directory

Try Directory.SetCurrentDirectory(“..\..\..\Projects1”)

MsgBox(“Switched current folder to “ & Directory.GetCurrentDirectory) Catch exc As FileNotFoundException

MsgBox(“Invalid folder specified, currrent directory is “ & vbCrLf & _ Directory.GetCurrentDirectory)

Catch exc As Exception

MsgBox(“Can’t access specified folder”) End Try

The code of Listing 13.2 handles the FileNotFoundException separately with the first Catch clause. All other exceptions are handled by the second Catch clause.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

574 Chapter 13 WORKING WITH FOLDERS AND FILES

GetDirectories

This method retrieves all the subfolders of a specific folder and returns their names as an array of strings:

Dirs = Directory.GetDirectories(path)

The path argument is the path of the folder whose subfolders you want to retrieve. The Dirs array that accepts the names of the subfolders must be declared with a statement like the following:

Dim Dirs() As String

Another form of the GetDirectories method allows you to specify search criteria for the folders you want to retrieve, and its syntax is

Dirs = Directory.GetDirectories(path, pattern)

This statement returns an array of strings with the names of the subfolders that match the search criteria. To retrieve all the subfolders of the C:\Windows folder with the string “System” in their names, use the statement

Dirs = Directory.GetDirectories(“C:\Windows”, “*SYSTEM*”)

This statement will go through the subfolders of C:\Windows and return those that contain the string “SYSTEM” (including “System32” and “MySystem”). The only special characters you can use in the criteria specification are the question mark, which stands for any single character, and the asterisk, which stands for any string. Listing 13.3 retrieves the names of the folders that contain the string “System” under the C:\WINNT folder and prints them in the Output window.

Listing 13.3: Retrieving Selected Subfolders of a Folder

Dim Dirs() As String

Dirs = Directory.GetDirectories(“C:\WINNT”, “*SYSTEM*”)

Dim dir As String

Console.WriteLine(Dirs.Length & “ folders match the pattern ‘*SYSTEM*’”)

For Each dir In Dirs

Console.WriteLine(dir)

Next

GetDirectoryRoot

This method returns the root part of the path passed as argument, and its syntax is

root = Directory.GetDirectoryRoot(path)

The path argument is a string, and the return value is also a string like “C:\” or “D:\”. Notice that the GetDirectoryRoot method doesn’t require that the path argument exists. It will return the name of the root folder of the specified path.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FOLDERS AND FILES 575

GetFiles

This method returns the names of the files in the specified folder as an array of strings. The syntax of the GetFiles method is

files = Directory.GetFiles(path)

where path is the path of the folder whose files you want to retrieve and files is an array of strings, which must be declared as follows:

Dim files() As String

This array will be dimensioned as it gets populated by the GetFiles method, so you don’t have to specify an upper bound when declaring the array.

Another form of the GetFiles method allows you to specify a pattern and retrieve only the names of the files that match the pattern. This form of the method accepts a second argument, which is a string similar to the pattern argument of the GetDirectories method:

files = Directory.GetFiles(path, pattern)

The statements in Listing 13.4 retrieve all the EXE files under the \WINNT folder and print their names in the Output window.

Listing 13.4: Retrieving Selected Files of a Folder

Dim files() As String

files = Directory.GetFiles(“C:\WINNT”, “*.EXE”) MsgBox(“Found “ & files.Length & “ EXE files”) Dim file As String

For Each file In files Console.WriteLine(file)

Next

GetFileSystemEntries

This method returns an array of all items (files and folders) in a path. The simplest form of the method is

items = Directory.GetFileSystemEntries(path)

where items is an array of FileSystemEntry, which you must declare as

Dim items() As String

As with the GetFiles method, you can specify a second argument, which filters the FileSystemEntry objects you want to retrieve:

Items = Directory.GetFileSystemEntries(path, matchFiles)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

576 Chapter 13 WORKING WITH FOLDERS AND FILES

To iterate through the items of a folder, associate a Directory object with this folder and use a loop like the following one:

Dim itm As String

For Each itm In Directory.GetFileSystemEntries(“C:\windows”)

Console.WriteLine(itm)

Next

Since the GetFileSystemEntries method returns an array of strings, how do we know that a specific member of the array is a file or a folder? To find out whether the current item is a file or a folder, you can use the Exists method of the Directory object. The File object, which is equivalent to the Directory object and is discussed in the following section, also exposes an Exists method. The loop shown in Listing 13.5 goes through the file system items in your C:\Program Files folder and displays their names, along with the indication “FOLDER” or “FILE,” depending on the type of each item.

Listing 13.5: Retrieving the File System Items of a Folder

Dim items() As String

Dim path As String = “c:\Program Files” items = Directory.GetFileSystemEntries(path) Dim itm As String

For Each itm In items

If Directory.Exists(itm) Then Console.WriteLine(“FOLDER “ & itm)

Else

Console.WriteLine(“FILE “ & itm) End If

Next

If you execute these statements, you will see a list like the following in the Output window (only considerably longer):

FOLDER c:\Program Files\Microsoft.NET

FOLDER c:\Program Files\HTML Help Workshop

FOLDER c:\Program Files\Microsoft Web Controls 0.6

FILE c:\Program Files\folder.htt

FILE c:\Program Files\desktop.ini

Note The GetDirectories, GetFiles, and GetFileSystemEntries methods return the items under the specified folder. If this folder contains subfolders (as is usually the case), the GetDirectories method won’t return any subfolders beyond the ones directly under the specified folder. To scan a folder recursively (scan all the subfolders under it to any depth), you must use a recursive routine. You will find examples of recursive folder scanning in Chapters 16 and 18.

GetLastAccessTime, SetLastAccessTime

These two methods are equivalent to the GetCreationTime and SetCreationTime methods, only they return and set the most recent date and time the file was accessed. The most common reason to

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

ACCESSING FOLDERS AND FILES 577

change the last access time for a file is so that the specific file will be excluded from a routine that deletes old files, or to include it in a list of backup files (with an automated procedure that backs up only the files that have been changed since their last backup).

GetLastWriteTime, SetLastWriteTime

These two methods are equivalent to the GetCreationTime and SetCreationTime methods, but they return and set the most recent date and time the file was written to.

GetLogicalDrives

This method returns an array of strings, which are the names of the logical drives on the computer. The statements in Listing 13.6 print the names of all logical drives.

Listing 13.6: Retrieving the Names of All Drives on the Computer

Dim drives() As String

drives = Directory.GetLogicalDrives Dim iDrive As Integer

For iDrive = 0 To drives.GetUpperBound(0) Console.WriteLine(drives(iDrive))

Next

When executed, these statements will produce a list like the following:

A:\

C:\

D:\

E:\

GetParent

This method retrieves an object that represents the properties of a folder’s parent folder. The syntax of the GetParent method is

parent = Directory.GetParent(path)

The return value is a DirectoryInfo object, and it must be declared with a statement like the following:

Dim parent As DirectoryInfo

The name of the parent folder, for example, is parent.Name and its full name is parent.FullName.

Move

This method moves an entire folder to another location in the file system; its syntax is

Directory.Move(source, destination)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com