- Introduction
- File Functions in Visual Basic
- Working with Text Files
- Random Files--Creating Your Own File Format
- INI Files
- From Here
File Functions in Visual Basic
Files are the basic organizational units of an operating system. There are many different types of files, from user-created documents to games to operating system commands. This section discusses some of the functions used to work with files from Visual Basic. Another method of accessing files, using the FileSystemObject interface, is discussed in Chapter 30, "Using VBScript." (This object interface was originally a part of VBScript but is now available in Visual Basic starting with version 6.) The functions discussed in this section have been around for a long time and are considered to be the "traditional" Visual Basic file functions.
See "Accessing the File System," p. 675.
Using Dir to Find and List Files
One useful file function is the Dir$ function. This function works like the Dir command at an MS-DOS command prompt. You can use the Dir$ function to retrieve a list of one or more operating system files that match a file specification or path. A path can include the name of a directory, a specific filename, or both. For example, C:\*.BAT is the path to all the files in the root directory of drive C having a BAT extension. The syntax of the Dir$ function is as follows:
stringvar = Dir$(path[,attributes])
Finding Files
One use of Dir$ is to determine whether a file exists. If you try to open a database or access a file that does not exist, an error occurs. However, you can use Dir$ first to check for a file's existence before opening it, as in the following example:
If Dir$("C:\MYFILE.TXT") = "" Then Msgbox "The file was not found. Please try again!" End If
The Dir$ function returns the filename without the full path if the specified file is found, or it returns an empty string if no files were found. The preceding line of code displays a message box if MYFILE.TXT does not exist in the root directory of drive C. If the file does exist, the string myfile.txt is returned. To make things even simpler, you can create a generic function that returns a Boolean value True if the given file exists:
Public Function bFileExists(sFile As String) As Boolean If Dir$(sFile) <> "" Then bFileExists = True Else bFileExists = False End Function
This function could then be used to check any filenames passed to the program by the user, as in the following example:
Dim sUserFile As String sUserFile = InputBox$("Enter the file name:") If Not bFileExists(sUserFile) Then MsgBox "The file does not exist. Please try again." End End If
Notice that the code sample ends the program if the file does not exist to prevent any errors that might occur later. Another way to handle this situation would be to keep asking the user for a filename until a valid filename is entered.
Listing Files and Folders
Another use of the Dir$ function is to return a list of files in the specified path. If you use the Dir command at an MS-DOS prompt, each matching file is listed onscreen. However, because the Dir$ function is designed to return only a single string variable, you have to use a loop and retrieve one filename at a time. (You also can display a list of files with a file list box, which is one of Visual Basic's default controls. These controls are covered extensively in Chapter 4, "Using Visual Basic's Default Controls.")
Suppose that your C:\DATA directory contains several picture files with a BMP (bitmap) extension. The path used to retrieve these files with the Dir$ function would be C:\DATA\*.BMP. You can use the following lines of code to retrieve the filenames and add them to a list box:
Dim sNextFile As String sNextFile = Dir$("C:\Data\*.BMP") While sNextFile <> "" lstPictureList.AddItem sNextFile sNextFile = Dir$ Wend
In the preceding example, notice that only the file path to Dir$ is supplied on the first call. Each subsequent call to Dir$ has no arguments, indicating that you want to use the previous file path and move to the next filename in the list. When no more files match, Dir$ returns an empty string and the While loop terminates.
CAUTION
When you use Dir$ in a loop, always exit the loop after an empty string is returned. If you try to make another call to Dir$ with no arguments, a runtime error occurs.
The second optional parameter of the Dir$ function is used to provide additional conditions (beyond the specified path) with which to select files. For example, using the constant vbDirectory returns only the subdirectories (or folders) in the specified path. The constant vbVolume causes Dir$ to return the specified drive's volume label. The available constants are summarized in Table 21.1. (You also can display a list of folders with a directory list box.)
Table 21.1
Constants Control the Behavior of the Dir$ Function
Constant |
Value |
Purpose |
vbNormal |
0 |
(Default value) |
vbHidden |
2 |
Include hidden files |
vbSystem |
4 |
Include system files |
vbVolume |
8 |
Return drive volume label |
vbDirectory |
16 |
Display subdirectories |
vbReadOnly |
1 |
Include read-only files |
NOTE
Constants can be added together if you want to use more than one. For example,
the following code finds the system, hidden, and read-only file IO.SYS on
a Windows 95 machine:
Debug.Print Dir$("C:\IO.SYS",vbHidden+vbSystem+vbReadOnly)
Note that the vbHidden constant refers to a file's attributes and not the Windows Explorer option that hides certain file types. You can view the attributes of a file by right-clicking the file's name and choosing Properties, as depicted in Figure 21.1, or by using the MS-DOS ATTRIB command.
File attributes, shown in Windows Explorer, can determine whether the Dir$ function returns a specific filename.
File-Manipulation Functions
As with the Dir$ function, most of the file-manipulation commands in Visual Basic are as straightforward as their MS-DOS equivalents, although with a few limitations. These file-manipulation commands are summarized in Table 21.2.
Table 21.2
Summary of File Functions
Action |
Syntax |
Copy a file |
FileCopy source, dest |
Delete one or more files |
Kill path |
Rename a file |
Name oldname As newname |
Create a new folder |
MkDir pathname |
Remove an empty folder |
RmDir pathname |
Change the current directory |
ChDir pathname |
Change the current drive |
ChDrive drive |
Several of these system functions are described in the following sections.
Copying Files
The FileCopy command has the limitation that you cannot use wildcards to specify multiple files. FileCopy can copy files locally or over a network, as shown in the following examples:
'The following line copies a file while changing its name: FileCopy "D:\My Documents\Hey Now.txt", "C:\DATA\TEST.TXT" 'The following lines of code use a network path for the source file: Dim sDest As String Dim sSource As String SSource = "\\myserver\deptfiles\budget98.XLS" SDest = "C:\DATA\BUDGET.XLS" FileCopy sSouce, sDest
The FileCopy statement automatically overwrites an existing file, unless the file is read-only or locked open by another application.
NOTE
When you copy files over a network or dial-up connection, using the On Error statement to trap errors is a good idea. For example, if the network is down or another user has the file exclusively locked, your program could bomb unexpectedly. You can easily provide an error trap and retry dialog, as described in Chapter 9, "Visual Basic Programming Fundamentals."
TIP
When you are performing file operations that take a long time (more than a few seconds), display an AVI file like Windows does. This capability is discussed in the section "Adding Video with the Animation Control" in Chapter 12, "Microsoft Common Controls."
Deleting Files
Visual Basic also allows you to delete files by using the Kill statement. Kill can use wildcards to specify multiple files, as in the following example:
Kill "D:\NewDir\*.doc"
Renaming Files
The Name statement is like MS-DOS's RENAME command, but can be used on only one file at a time:
Name oldname As newname
You also can use Name like the MOVE command in MS-DOS if the specified paths are different:
'Moves the file to a new directory MkDir "D:\NewDir" Name "C:\Windows\Desktop\TEST1.TXT" AS "D:\NewDir\TEST2.TXT"
In the preceding example, note the MkDir statement, which you probably have guessed is used to create a new directory. The MkDir and RmDir statements add and remove directories, just like their MD and RD counterparts in MS-DOS.
Setting the Current Directory
In the examples discussed so far, the path has always included the drive and directory. However, as you may recall from using MS-DOS, during the context of your MS-DOS session, you are always "in" a certain directory, which is usually displayed to the left of the MS-DOS cursor. For example, if you type CD \WINDOWS, you can rename, copy, or delete files within the WINDOWS directory without specifying C:\WINDOWS in the pathname. The same concept of a current directory applies to Visual Basic. By using the ChDir and ChDrive statements, you can set the current working directory on each drive and switch between current drives, eliminating the need to specify the full path for each file operation:
'Change to the desired directory and drive and rename a file chdir "C:\Windows\Desktop" chdrive "C:" Name "TEST1.TXT" As "TEST2.TXT" 'Delete a file in the current directory ChDrive "D:" ChDir "D:\DATA" Kill "OLDDATA.DAT"
Performing deletes can be dangerous if you don't know the current directory. Fortunately, Visual Basic offers a function that provides this value: the CurDir$ function. The syntax of CurDir$ is the following:
stringvar = CurDir$([Drive])
NOTE
You can use the Left$ function to get the current drive, as in the
following example:
sDriveLetter = Left$(CurDir$(),1)
Launching Other Programs with the Shell Function
From time to time, you may need to launch another Windows program from your Visual Basic code. For example, you could use Visual Basic to schedule a data transfer or file cleanup. You could easily do so by checking the current system time and then running the secondary program when appropriate. You can run other programs by using the Shell function. The syntax for Shell is as follows:
DoubleVar = Shell(pathname[,windowstyle])
The following lines of Visual Basic code use Shell to run Notepad and bring up a text file called README.TXT:
Dim dTaskID As Double dTaskID = Shell("Notepad D:\readme.txt", vbNormalFocus)
The first parameter of Shell is the command to be executed, and the second optional parameter is the window style. In the preceding example, the constant vbNormalFocus tells the Shell statement to run Notepad in a normal window with focus. The constant specifies two attributes of the new window: style and focus. Style describes how the window will be displayed (normal, minimized, maximized, or hidden), and the focus describes whether the application will become the foreground application (only one running application can have the focus). The default window style is minimized with focus. This means the shelled application does not obscure another application's window, but the shelled program has the focus.
Launching another application with Shell is easy. If you need to wait for it to complete before your Visual Basic code continues, you need to use slightly more complex code with some additional Windows API calls. This specific API example is discussed in Chapter 20, "Accessing the Windows API."
See "Waiting on a Program to Finish Running," p. 461.
Locating Files Relative to Your Application
When you work with files in Visual Basic, "hard-coding" a file or folder name within your program is never a good idea. A commercial application such as Microsoft Office lets you change the default installation directory to anything you want. Even if you install the application in an off-the-wall location such as D:\JUNK123\, it still can find all its other files (such as templates and clip art) and function normally.
Likewise, your applications will be more successful and professional if they can survive on any drive or installation path. If you include files beyond the actual program EXE (such as a database), you can add some minor coding so that your program can locate these files in a manner that is transparent to the user.
Figure 21.2 shows an album selection screen. This program allows the user to click an album image to play the album. The program is designed to run from a CD-ROM drive. This means the path to the program might be D:\TUNES\TUNES.EXE if your CD-ROM drive letter is D. The album cover pictures and database information are also stored in the \TUNES subdirectory on the CD-ROM.
When your program is running from an unknown location, such as a mapped network drive or CD-ROM, use App.Path to locate what you need.
For the program to always find the images, regardless of the CD-ROM drive letter, it uses the Path property of the App object (App.Path), as in the following example:
'Open database Set db = OpenDatabase(App.Path & "\albums.mdb") 'Load image Set picture1 = LoadPicture(App.Path & "\Picture1.GIF")
App.Path returns the directory in which the application is running. In the preceding example, the returned value is D:\TUNES or whichever directory the TUNES.EXE file is located in.
NOTE
After you have saved your project and are working in the Visual Basic IDE, App.Path returns the path to your project's directory (with the .VBP file). If the project hasn't yet been saved, App.Path returns the current directory.
In the preceding examples, notice that you have to add a backslash before specifying the filename. App.Path doesn't add the final backslash unless it returns the root directory. You can use the Right$ function to check for this at the beginning of your program:
'Sets sAppPath (assumed to be a public variable) for use later in the program sAppPath = App.Path If Right$(sAppPath,1) <> "\" then sAppPath = sAppPath & "\" 'Later in the program: Dim sDBLocation As String sDBLocation = sAppPath & "finance.mdb"
Some programmers use the ChDir command (discussed earlier) to change the current directory to App.Path at the beginning of the program. I tend to stay away from this command because it also may affect other Windows programs.
TIP
If your application uses many files spread across several directories and drives, you should take the next step and keep file locations in an INI file or database. (See "Understanding INI Files" later in the chapter.)