- •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
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 |