- •Using Your Sybex Electronic Book
- •Acknowledgments
- •Contents at a Glance
- •Introduction
- •Who Should Read This Book?
- •How About the Advanced Topics?
- •The Structure of the Book
- •How to Reach the Author
- •The Integrated Development Environment
- •The Start Page
- •Project Types
- •Your First VB Application
- •Making the Application More Robust
- •Making the Application More User-Friendly
- •The IDE Components
- •The IDE Menu
- •The Toolbox Window
- •The Solution Explorer
- •The Properties Window
- •The Output Window
- •The Command Window
- •The Task List Window
- •Environment Options
- •A Few Common Properties
- •A Few Common Events
- •A Few Common Methods
- •Building a Console Application
- •Summary
- •Building a Loan Calculator
- •How the Loan Application Works
- •Designing the User Interface
- •Programming the Loan Application
- •Validating the Data
- •Building a Math Calculator
- •Designing the User Interface
- •Programming the MathCalculator App
- •Adding More Features
- •Exception Handling
- •Taking the LoanCalculator to the Web
- •Working with Multiple Forms
- •Working with Multiple Projects
- •Executable Files
- •Distributing an Application
- •VB.NET at Work: Creating a Windows Installer
- •Finishing the Windows Installer
- •Running the Windows Installer
- •Verifying the Installation
- •Summary
- •Variables
- •Declaring Variables
- •Types of Variables
- •Converting Variable Types
- •User-Defined Data Types
- •Examining Variable Types
- •Why Declare Variables?
- •A Variable’s Scope
- •The Lifetime of a Variable
- •Constants
- •Arrays
- •Declaring Arrays
- •Initializing Arrays
- •Array Limits
- •Multidimensional Arrays
- •Dynamic Arrays
- •Arrays of Arrays
- •Variables as Objects
- •So, What’s an Object?
- •Formatting Numbers
- •Formatting Dates
- •Flow-Control Statements
- •Test Structures
- •Loop Structures
- •Nested Control Structures
- •The Exit Statement
- •Summary
- •Modular Coding
- •Subroutines
- •Functions
- •Arguments
- •Argument-Passing Mechanisms
- •Event-Handler Arguments
- •Passing an Unknown Number of Arguments
- •Named Arguments
- •More Types of Function Return Values
- •Overloading Functions
- •Summary
- •The Appearance of Forms
- •Properties of the Form Control
- •Placing Controls on Forms
- •Setting the TabOrder
- •VB.NET at Work: The Contacts Project
- •Anchoring and Docking
- •Loading and Showing Forms
- •The Startup Form
- •Controlling One Form from within Another
- •Forms vs. Dialog Boxes
- •VB.NET at Work: The MultipleForms Project
- •Designing Menus
- •The Menu Editor
- •Manipulating Menus at Runtime
- •Building Dynamic Forms at Runtime
- •The Form.Controls Collection
- •VB.NET at Work: The DynamicForm Project
- •Creating Event Handlers at Runtime
- •Summary
- •The TextBox Control
- •Basic Properties
- •Text-Manipulation Properties
- •Text-Selection Properties
- •Text-Selection Methods
- •Undoing Edits
- •VB.NET at Work: The TextPad Project
- •Capturing Keystrokes
- •The ListBox, CheckedListBox, and ComboBox Controls
- •Basic Properties
- •The Items Collection
- •VB.NET at Work: The ListDemo Project
- •Searching
- •The ComboBox Control
- •The ScrollBar and TrackBar Controls
- •The ScrollBar Control
- •The TrackBar Control
- •Summary
- •The Common Dialog Controls
- •Using the Common Dialog Controls
- •The Color Dialog Box
- •The Font Dialog Box
- •The Open and Save As Dialog Boxes
- •The Print Dialog Box
- •The RichTextBox Control
- •The RTF Language
- •Methods
- •Advanced Editing Features
- •Cutting and Pasting
- •Searching in a RichTextBox Control
- •Formatting URLs
- •VB.NET at Work: The RTFPad Project
- •Summary
- •What Is a Class?
- •Building the Minimal Class
- •Adding Code to the Minimal Class
- •Property Procedures
- •Customizing Default Members
- •Custom Enumerations
- •Using the SimpleClass in Other Projects
- •Firing Events
- •Shared Properties
- •Parsing a Filename String
- •Reusing the StringTools Class
- •Encapsulation and Abstraction
- •Inheritance
- •Inheriting Existing Classes
- •Polymorphism
- •The Shape Class
- •Object Constructors and Destructors
- •Instance and Shared Methods
- •Who Can Inherit What?
- •Parent Class Keywords
- •Derived Class Keyword
- •Parent Class Member Keywords
- •Derived Class Member Keyword
- •MyBase and MyClass
- •Summary
- •On Designing Windows Controls
- •Enhancing Existing Controls
- •Building the FocusedTextBox Control
- •Building Compound Controls
- •VB.NET at Work: The ColorEdit Control
- •VB.NET at Work: The Label3D Control
- •Raising Events
- •Using the Custom Control in Other Projects
- •VB.NET at Work: The Alarm Control
- •Designing Irregularly Shaped Controls
- •Designing Owner-Drawn Menus
- •Designing Owner-Drawn ListBox Controls
- •Using ActiveX Controls
- •Summary
- •Programming Word
- •Objects That Represent Text
- •The Documents Collection and the Document Object
- •Spell-Checking Documents
- •Programming Excel
- •The Worksheets Collection and the Worksheet Object
- •The Range Object
- •Using Excel as a Math Parser
- •Programming Outlook
- •Retrieving Information
- •Recursive Scanning of the Contacts Folder
- •Summary
- •Advanced Array Topics
- •Sorting Arrays
- •Searching Arrays
- •Other Array Operations
- •Array Limitations
- •The ArrayList Collection
- •Creating an ArrayList
- •Adding and Removing Items
- •The HashTable Collection
- •VB.NET at Work: The WordFrequencies Project
- •The SortedList Class
- •The IEnumerator and IComparer Interfaces
- •Enumerating Collections
- •Custom Sorting
- •Custom Sorting of a SortedList
- •The Serialization Class
- •Serializing Individual Objects
- •Serializing a Collection
- •Deserializing Objects
- •Summary
- •Handling Strings and Characters
- •The Char Class
- •The String Class
- •The StringBuilder Class
- •VB.NET at Work: The StringReversal Project
- •VB.NET at Work: The CountWords Project
- •Handling Dates
- •The DateTime Class
- •The TimeSpan Class
- •VB.NET at Work: Timing Operations
- •Summary
- •Accessing Folders and Files
- •The Directory Class
- •The File Class
- •The DirectoryInfo Class
- •The FileInfo Class
- •The Path Class
- •VB.NET at Work: The CustomExplorer Project
- •Accessing Files
- •The FileStream Object
- •The StreamWriter Object
- •The StreamReader Object
- •Sending Data to a File
- •The BinaryWriter Object
- •The BinaryReader Object
- •VB.NET at Work: The RecordSave Project
- •The FileSystemWatcher Component
- •Properties
- •Events
- •VB.NET at Work: The FileSystemWatcher Project
- •Summary
- •Displaying Images
- •The Image Object
- •Exchanging Images through the Clipboard
- •Drawing with GDI+
- •The Basic Drawing Objects
- •Drawing Shapes
- •Drawing Methods
- •Gradients
- •Coordinate Transformations
- •Specifying Transformations
- •VB.NET at Work: Plotting Functions
- •Bitmaps
- •Specifying Colors
- •Defining Colors
- •Processing Bitmaps
- •Summary
- •The Printing Objects
- •PrintDocument
- •PrintDialog
- •PageSetupDialog
- •PrintPreviewDialog
- •PrintPreviewControl
- •Printer and Page Properties
- •Page Geometry
- •Printing Examples
- •Printing Tabular Data
- •Printing Plain Text
- •Printing Bitmaps
- •Using the PrintPreviewControl
- •Summary
- •Examining the Advanced Controls
- •How Tree Structures Work
- •The ImageList Control
- •The TreeView Control
- •Adding New Items at Design Time
- •Adding New Items at Runtime
- •Assigning Images to Nodes
- •Scanning the TreeView Control
- •The ListView Control
- •The Columns Collection
- •The ListItem Object
- •The Items Collection
- •The SubItems Collection
- •Summary
- •Types of Errors
- •Design-Time Errors
- •Runtime Errors
- •Logic Errors
- •Exceptions and Structured Exception Handling
- •Studying an Exception
- •Getting a Handle on this Exception
- •Finally (!)
- •Customizing Exception Handling
- •Throwing Your Own Exceptions
- •Debugging
- •Breakpoints
- •Stepping Through
- •The Local and Watch Windows
- •Summary
- •Basic Concepts
- •Recursion in Real Life
- •A Simple Example
- •Recursion by Mistake
- •Scanning Folders Recursively
- •Describing a Recursive Procedure
- •Translating the Description to Code
- •The Stack Mechanism
- •Stack Defined
- •Recursive Programming and the Stack
- •Passing Arguments through the Stack
- •Special Issues in Recursive Programming
- •Knowing When to Use Recursive Programming
- •Summary
- •MDI Applications: The Basics
- •Building an MDI Application
- •Built-In Capabilities of MDI Applications
- •Accessing Child Forms
- •Ending an MDI Application
- •A Scrollable PictureBox
- •Summary
- •What Is a Database?
- •Relational Databases
- •Exploring the Northwind Database
- •Exploring the Pubs Database
- •Understanding Relations
- •The Server Explorer
- •Working with Tables
- •Relationships, Indices, and Constraints
- •Structured Query Language
- •Executing SQL Statements
- •Selection Queries
- •Calculated Fields
- •SQL Joins
- •Action Queries
- •The Query Builder
- •The Query Builder Interface
- •SQL at Work: Calculating Sums
- •SQL at Work: Counting Rows
- •Limiting the Selection
- •Parameterized Queries
- •Calculated Columns
- •Specifying Left, Right, and Inner Joins
- •Stored Procedures
- •Summary
- •How About XML?
- •Creating a DataSet
- •The DataGrid Control
- •Data Binding
- •VB.NET at Work: The ViewEditCustomers Project
- •Binding Complex Controls
- •Programming the DataAdapter Object
- •The Command Objects
- •The Command and DataReader Objects
- •VB.NET at Work: The DataReader Project
- •VB.NET at Work: The StoredProcedure Project
- •Summary
- •The Structure of a DataSet
- •Navigating the Tables of a DataSet
- •Updating DataSets
- •The DataForm Wizard
- •Handling Identity Fields
- •Transactions
- •Performing Update Operations
- •Updating Tables Manually
- •Building and Using Custom DataSets
- •Summary
- •An HTML Primer
- •HTML Code Elements
- •Server-Client Interaction
- •The Structure of HTML Documents
- •URLs and Hyperlinks
- •The Basic HTML Tags
- •Inserting Graphics
- •Tables
- •Forms and Controls
- •Processing Requests on the Server
- •Building a Web Application
- •Interacting with a Web Application
- •Maintaining State
- •The Web Controls
- •The ASP.NET Objects
- •The Page Object
- •The Response Object
- •The Request Object
- •The Server Object
- •Using Cookies
- •Handling Multiple Forms in Web Applications
- •Summary
- •The Data-Bound Web Controls
- •Simple Data Binding
- •Binding to DataSets
- •Is It a Grid, or a Table?
- •Getting Orders on the Web
- •The Forms of the ProductSearch Application
- •Paging Large DataSets
- •Customizing the Appearance of the DataGrid Control
- •Programming the Select Button
- •Summary
- •How to Serve the Web
- •Building a Web Service
- •Consuming the Web Service
- •Maintaining State in Web Services
- •A Data-Driven Web Service
- •Consuming the Products Web Service in VB
- •Summary
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 |
