Home > Articles > Programming > Visual Basic

  • Print
  • + Share This
This chapter is from the book

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.

Figure 21.1

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."

See "Using the On Error Statement," p. 219.

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.

Figure 21.2

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.)

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020