Working with the File System in VB6

Level:
Level2

The file system is what makes up everything that Windows sees on a disk drive. This includes files and folders along with these file and folders properties. Using Visual Basic commands we can do many if not almost anything you could want with the file system. Such as copying files, changing file properties, deleting, moving, etc, etc. Along with this you can use the VB6 file commands to do things such as checking creation dates, last modified dates, file size, and many other useful things. Over all you should be able to do almost anything you could do at a DOS prompt in the VB6 environment. If you have other useful commands that should be added to this tutorial let me know in the comments section below!

 

VB provides a set of statements that perform DOS-like (or Windows command line-like) commands. These commands are listed and described in the table below:

 

 

VB Statement

Equivalent DOS/Windows Command Line Command

 

Description

 

Syntax

MkDir

MKDIR or MD

Creates (makes) a directory

MkDir pathname

RmDir

RMDIR or RD

Removes (deletes) a directory

RmDir pathname

ChDrive

drive:

(like typing A: on the command line)

Changes the current drive

ChDrive drive

ChDir

CHDIR or CD

Changes the current directory

ChDir drive

Kill

ERASE or DEL

Deletes a file

Kill filespec

Name

RENAME or REN

Renames a file

Name oldfilespec As newfilespec

FileCopy

COPY

Copies a file

FileCopy oldfilespec, newfilespec

 

In the syntax above, pathname is a string expression specifying a valid path (it may optionally include the drive); drive is a string expression specifying a drive letter; and filespec, oldfilespec, and newfilespec are string expressions that specify a file (they may optionally include the drive and path).

 

Following is a set of functions that can be used with files (all are functions except SetAttr, which is a statement):

 

Function

Description

Syntax

FileDateTime

Returns a date/time value indicating the date and time that a file was created or last modified.

FileDateTime(filespec)

GetAttr

Returns an integer representing the attributes of a file, directory, or folder

GetAttr(filespec)

SetAttr

Statement that lets you specify the attributes for a file

SetAttr(filespec, attributes)

CurDir$ (or CurDir)

Returns a string that indicates the current path for a specified disk drive. In the syntax on the right, drivename is a string expression that specifies a valid disk drive designation

CurDir$(drivename)

Dir$ (or DIr)

Returns a string that indicates a file or directory matching specified conditions

Dir$(filespec [,attributes])

FileLen

Returns a Long specifying the length of a file in bytes. If the specified file is open when the FileLen function is called, the value returned represents the size of the file immediately before it was opened.

FileLen(pathname)

LOF

Returns a Long representing the size, in bytes, of a file opened using the Open statement.

FileLen(filenumber)

 

The return value of GetAttr and the attributes argument of SetAttr and Dir$ can have any of the following values (not all values are valid for all functions):

 

Constant

Value

vbNormal

0

vbReadOnly

1

vbHidden

2

VbSystem

4

vbVolume

8

vbDirectory

16

vbArchive

32

 

Common Uses of the Dir$ Function

 

The Dir$ function is commonly used to test for the existence of a particular file, test for the existence of a particular directory (folder), and to generate a list of files contained in a particular directory.

 

To see if a particular file exists, use that filename as the argument to the Dir$ function. If the result is the empty string (""), then the file does NOT exist – otherwise, it does:

 

If DIr$("C:\SomeFolder\MyFile.txt") = "" Then

Msgbox "File does not exist."

Else

Msgbox "File exists."

End If

 

To see if a particular directory (folder) exists, use that directory path as the first argument to the Dir$ function, and the vbDirectory attribute as the second argument. If the result is the zero-length string (""), then the directory does NOT exist – otherwise, it does:

 

If DIr$("C:\SomeFolder", vbDirectory) = "" Then

Msgbox "Directory does not exist."

Else

Msgbox " Directory exists."

End If

 

To generate a list of files contained in a particular directory, you use a path/filename specification with a wildcard as the argument in an initial call to Dir$; then you make repeated calls to Dir$ with no argument until Dir$ returns an zero-length string (""). This can be accomplished with the following code:

 

Dim strCurrentFile As String

 

strCurrentFile = Dir$("C:\SomeDir\*.txt")

Do Until strCurrentFile = ""

Print strCurrentFile

strCurrentFile = Dir$()

Loop

 

 

Sample Program

 

As a vehicle to demonstrate commonly used file system commands and functions, the tasks in a student exercise to practice MS-DOS commands has become the work to be done by the sample program.

 

Let us take a look at the original student exercise. The students were given a floppy disk containing the following files, all in the root directory:

 

 

The students were instructed to make six directories on their disk and move the indicated files to their proper directory as shown below. When done with this step, there should be NO files in the root directory.

 

Create a directory called:

For files with these extensions:

SYSTEM

.SYS

COMMAND

.COM

EXECUTE

.EXE

INITIAL

.INI

TEXT

.TXT

WRITE

.WRI

 

To do this step they would have to do the following:

 

First, make the directories:

 

MD SYSTEM

MD COMMAND

MD EXECUTE

MD INITIAL

MD TEXT

MD WRITE

 

Next, they would have to move the appropriate set of files from the root to the proper directory. This could be accomplished with either a set of MOVE commands or a set of COPY and DELETE combinations:

 

MOVE A:\*.SYS A:\SYSTEM

MOVE A:\*.COM A:\COMMAND

MOVE A:\*.EXE A:\EXECUTE

MOVE A:\*.INI A:\INITIAL

MOVE A:\*.TXT A:\TEXT

MOVE A:\*.WRI A:\WRITE

 

- or -

 

COPY A:\*.SYS A:\SYSTEM

DEL A:\*.SYS

COPY A:\*.COM A:\COMMAND

DEL A:\*.COM

COPY A:\*.EXE A:\EXECUTE

DEL A:\*.EXE

COPY A:\*.INI A:\INITIAL

DEL A:\*.INI

COPY A:\*.TXT A:\TEXT

DEL A:\*.TXT

COPY A:\*.WRI A:\WRITE

DEL A:\*.WRI

 

For the last step, they were instructed as follows:

 

Below the SYSTEM subdirectory, create a directory called EXE_INI. Place copies of the .EXE and .INI files there. Below the INITIAL subdirectory, create a directory call TXT_WRI. Place copies of the .TXT and .WRI files there.

 

To do this, they would have to issue the following commands:

 

MD A:\SYSTEM\EXE_INI

COPY A:\EXECUTE\*.EXE A:\SYSTEM\EXE_INI

COPY A:\INITIAL\*.INI A:\SYSTEM\EXE_INI

 

MD A:\INITIAL\TXT_WRI

COPY A:\TEXT\*.TXT A:\INITIAL\TXT_WRI

COPY A:\WRITE\*.INI A:\ INITIAL\TXT_WRI

 

The student would then turn their disk into the instructor, who would check to make sure that all the proper directories were created and that the files were in the right place.

 

As a follow-up exercise, students were given the disks back and asked to restore the disk back to its original state – i.e., all files back in the root with no subdirectories.

 

To do this, they would have to move the *.SYS, *.COM, *.EXE, *.INI, *.TXT, and *.WRI files from their respective top-level directories back to the root. This could be accomplished with the following MS-DOS (Windows command-line) commands:

 

MOVE A:\SYSTEM\*.* A:\

MOVE A:\COMMAND\*.* A:\

MOVE A:\EXECUTE\*.* A:\

MOVE A:\INITIAL\*.* A:\

MOVE A:\TEXT\*.* A:\

MOVE A:\WRITE\*.* A:\

 

At this point, the COMMAND, EXECUTE, TEXT, and WRITE subdirectories are cleared out, so they could be removed with the "remove directory" command (RMDIR or RD) as follows:

 

RD A:\COMMAND

RD A:\EXECUTE

RD A:\TEXT

RD A:\WRITE

 

However, since second-level directories were created below both the SYSTEM and the INITIAL directories, those directories must be cleared out before they can be removed (the RD command will only work if the directory to be removed is empty).

 

Therefore, the files in the EXE_INI directory below the SYSTEM directory must be deleted:

 

DEL A:\SYSTEM\EXE_INI\*.*

 

Then the EXE_INI directory can be removed:

 

RD A:\SYSTEM\EXE_INI

 

Then the top-level SYSTEM directory can be removed:

 

RD A:\SYSTEM

 

A similar set of commands is necessary to clear the INITIAL directory:

 

DEL A:\INITIAL\TXT_WRI\*.*

RD A:\INITIAL\TXT_WRI

RD A:\INITIAL

 

At this point, the exercise would be complete and the disk could be turned back into the instructor.

 

To do the sample project that implements these actions, you need a "clean" (empty) floppy disk. The sample files shown above (the .SYS, .INI, etc.) should then be copied to that disk. The project download below, when unzipped, contains a folder called "FileSysDemoFiles", from where the files can be copied. (As an alternative, you can simply make empty files using Notepad and save them with those names, and then copy them to a floppy. For the purpose of this exercise, the content of these files do not matter; for example, the "exe" and "com" files need not be valid executables.)

 

The sample project is a modified "Try It" program. The "Clear" button was changed to "Reset" (the caption was changed "Reset" and the name was changed to "cmdReset").

 

 

The "Try It" button implements the first part of the exercise (makes the subdirectories and moves and copies the files to their proper locations). The "Reset" button implements the second part of the exercise (puts all files back to the root directory and removes all of the subdirectories).

 

The cmdTryIt_Click code, as well as a Sub called CopyOrMoveFiles (to facilitate the copying and moving of files) is shown below. The code is heavily commented to aid in the understanding of what the code is doing.

 

You will notice that two statements, "DoEvents" and "Refresh" are used throughout the procedure.

 

The DoEvents statement "yields execution so that the operating system can process other events". DoEvents is typically used to break up processor-intensive operations (such as all the I/O this program is doing) so that the system does not appear to freeze up and so that you can do other things (such as run another program) while the VB program is running.

 

"Refresh" is actually a method of the form and could have been coded as "Me.Refresh" or "frmTest.Refresh". The Refresh method forces the form to repaint itself. The Refresh method was used to ensure that each "Print" message is displayed at the desired time (during processor-intensive operations, the form does not always automatically repaint itself when we want it to).

 

Private Sub cmdTryIt_Click()

On Error GoTo cmdTryIt_Click_Error

Cls

' Make the top-level subdirectories below the root with the MkDir statement ...

MkDir "A:\SYSTEM"

MkDir "A:\COMMAND"

MkDir "A:\EXECUTE"

MkDir "A:\INITIAL"

MkDir "A:\TEXT"

MkDir "A:\WRITE"

' Free up the OS for a sec and ensure message is displayed ...

DoEvents

Print "Top-level directories have been made."

Refresh

' To faciliate the moving of the files to their proper directories, a Sub named

' CopyOrMoveFiles was written. The Sub takes four arguments: (1) source path,

' (2) target path, (3) file extension, and (4) a one-character code indicating

' whether the files should be moved ("M") or copied ("C"). The Sub is called six

' times, once for each file type to be moved from the root to its proper directory.

CopyOrMoveFiles "A:\", "A:\SYSTEM", "SYS", "M"

CopyOrMoveFiles "A:\", "A:\COMMAND", "COM", "M"

CopyOrMoveFiles "A:\", "A:\EXECUTE", "EXE", "M"

CopyOrMoveFiles "A:\", "A:\INITIAL", "INI", "M"

CopyOrMoveFiles "A:\", "A:\TEXT", "TXT", "M"

CopyOrMoveFiles "A:\", "A:\WRITE", "WRI", "M"

' Free up the OS for a sec and ensure message is displayed ...

DoEvents

Print "Files have been moved from root to top-level directories."

Refresh

' Create the EXE_INI directory below the SYSTEM directory with MkDir ...

MkDir "A:\SYSTEM\EXE_INI"

Print "Second-level directory for EXE and INI files has been made."

' Use the "CopyOrMoveFiles" Sub to copy the EXEs and INIs to the

' newly-created directory ...

CopyOrMoveFiles "A:\EXECUTE", "A:\SYSTEM\EXE_INI", "EXE", "C"

CopyOrMoveFiles "A:\INITIAL", "A:\SYSTEM\EXE_INI", "INI", "C"

' Free up the OS for a sec and ensure message is displayed ...

DoEvents

Print "Files have been copied to EXE_INI directory."

Refresh

 

' Create the TXT_WRI directory below the INITIAL directory with MkDir ...

MkDir "A:\INITIAL\TXT_WRI"

Print "Second-level directory for TXT and WRI files has been made."

' Use the "CopyOrMoveFiles" Sub to copy the TXTs and WRIs to the

' newly-created directory ...

CopyOrMoveFiles "A:\TEXT", "A:\INITIAL\TXT_WRI", "TXT", "C"

CopyOrMoveFiles "A:\WRITE", "A:\INITIAL\TXT_WRI", "WRI", "C"

' Free up the OS for a sec and ensure message is displayed ...

DoEvents

Print "Files have been copied to TXT_WRI directory."

Refresh

Print "Done."

 

Exit Sub

 

cmdTryIt_Click_Error:

MsgBox "The following error has occurred:" & vbNewLine _

& "Error # " & Err.Number & " - " & Err.Description, _

vbCritical, _

"File System Commands Demo - Error"

 

End Sub

 

 

Private Sub CopyOrMoveFiles(pstrSourcePath As String, _

pstrTargetPath As String, _

pstrExtension As String, _

pstrCopyOrMoveCode As String)

 

' This Sub takes four arguments: (1) source path, (2) target path, (3) file extension,

' and (4) a one-character code indicating whether the files should be moved ("M") or

' copied ("C").

 

Dim strCurrentFile As String

Dim strPattern As String

Dim strSourceFile As String

Dim strTargetFile As String

' If the source path does not already have a backslash at

' the end of it, add one ...

If Right$(pstrSourcePath, 1) <> "\" Then

pstrSourcePath = pstrSourcePath & "\"

End If

 

' If the target path does not already have a backslash at

' the end of it, add one ...

If Right$(pstrTargetPath, 1) <> "\" Then

pstrTargetPath = pstrTargetPath & "\"

End If

' Create the "source pattern" by concatenating the source path, "*.", and

' the extension. For example, if "A:\" was passed in as the source path and

' "SYS" was passed in as the extension, the value of strPattern would be

' "A:\*.SYS".

strPattern = pstrSourcePath & "*." & pstrExtension

 

' Use the pattern created above as the initial argument to the Dir$ function.

' The strCurrentFile variable will be used to hold the matching files (one at

' a time, as returned by successive calls to the Dir$ function).

strCurrentFile = Dir$(strPattern)

' Set up a loop to copy the matching files from the source path to the target

' path. The loop will stop when there are no more matching files.

Do Until strCurrentFile = ""

' Create the source file name that will be used in the FileCopy statement

' by concatenating the source path with the filename last returned by the

' Dir$ function. For example, if the source path was "A:\", and the current

' filename returned by Dir$ was "TESTSYS1.SYS", then the value of strSourceFile

' would be "A:\TESTSYS1.SYS".

strSourceFile = pstrSourcePath & strCurrentFile

' Create the target file name that will be used in the FileCopy statement

' by concatenating the target path with the filename last returned by the

' Dir$ function. For example, if the target path was "A:\SYSTEM\", and the

' current filename returned by Dir$ was "TESTSYS1.SYS", then the value of

' strTargetFile would be "A:\SYSTEM\TESTSYS1.SYS".

strTargetFile = pstrTargetPath & strCurrentFile

' Use FileCopy to copy the source file to its target destination ...

FileCopy strSourceFile, strTargetFile

' Get the next matching file by calling the Dir$ function with no arguments.

strCurrentFile = Dir$()

Loop

' If the "Copy or Move code" passed in was "M" (for move), then we need to delete

' the files that we just copied to a new location. Since the native VB file I/O

' statements do not include a "move file" statement specifically, a move must be

' be accomplished by first copying a file to its new destination, then deleting it

' from its original location. The Kill statement is used to delete one or more files

' (it will accept a file specification that uses a pattern). For example, if the

' variable strPattern contained "A:\*.SYS", the Kill statement below would be

' equivalent to the MS-DOS/Windows command-line command "DEL A:\*.SYS".

If pstrCopyOrMoveCode = "M" Then

Kill strPattern

End If

End Sub

 

After the cmdTryIt_Click event procedure has run, the form should look like this:

 

 

 

The cmdReset_Click code, which implements the follow-up part of the student exercise (to restore the disk back to its original state – i.e., all files back in the root with no subdirectories) is shown below. The code is heavily commented to aid in the understanding of what the code is doing.

 

Private Sub cmdReset_Click()

On Error GoTo cmdReset_Click_Error

Cls

' Delete all of the files in the EXE_INI directory below the SYSTEM directory ...

Kill "A:\SYSTEM\EXE_INI\*.*"

' Now that the EXE_INI directory is clear, remove it with RmDir

RmDir "A:\SYSTEM\EXE_INI"

' Use the CopyOrMoveFiles Sub to move the SYS files from the SYSTEM directory

' back to the root ...

CopyOrMoveFiles "A:\SYSTEM", "A:\", "SYS", "M"

' Moving the SYS files out of the SYSTEM directory should have cleared it, so

' it now can be removed with RmDir ...

RmDir "A:\SYSTEM\"

' Free up the OS for a sec and ensure message is displayed ...

DoEvents

Print "SYSTEM directory has been cleared; files moved back to root."

Refresh

 

' Use the CopyOrMoveFiles Sub to move the COM files from the COMMAND directory

' back to the root ...

CopyOrMoveFiles "A:\COMMAND", "A:\", "COM", "M"

' Moving the COM files out of the COMMAND directory should have cleared it, so

' it now can be removed with RmDir ...

RmDir "A:\COMMAND"

' Free up the OS for a sec and ensure message is displayed ...

DoEvents

Print "COMMAND directory has been cleared; files moved back to root."

Refresh

' Use the CopyOrMoveFiles Sub to move the EXE files from the EXECUTE directory

' back to the root ...

CopyOrMoveFiles "A:\EXECUTE", "A:\", "EXE", "M"

' Moving the EXE files out of the EXECUTE directory should have cleared it, so

' it now can be removed with RmDir ...

RmDir "A:\EXECUTE"

 

' Free up the OS for a sec and ensure message is displayed ...

DoEvents

Print "EXECUTE directory has been cleared; files moved back to root."

Refresh

' Delete all of the files in the TXT_WRI directory below the INITIAL directory ...

Kill "A:\INITIAL\TXT_WRI\*.*"

' Now that the TXT_WRI directory is clear, remove it with RmDir

RmDir "A:\INITIAL\TXT_WRI"

' Use the CopyOrMoveFiles Sub to move the INI files from the INITIAL directory

' back to the root ...

CopyOrMoveFiles "A:\INITIAL", "A:\", "INI", "M"

' Moving the INI files out of the INITIAL directory should have cleared it, so

' it now can be removed with RmDir ...

RmDir "A:\INITIAL"

 

' Free up the OS for a sec and ensure message is displayed ...

DoEvents

Print "INITIAL directory has been cleared; files moved back to root."

Refresh

' Use the CopyOrMoveFiles Sub to move the TXT files from the TEXT directory

' back to the root ...

CopyOrMoveFiles "A:\TEXT", "A:\", "TXT", "M"

' Moving the TXT files out of the TEXT directory should have cleared it, so

' it now can be removed with RmDir ...

RmDir "A:\TEXT"

 

' Free up the OS for a sec and ensure message is displayed ...

DoEvents

Print "TEXT directory has been cleared; files moved back to root."

Refresh

' Use the CopyOrMoveFiles Sub to move the WRI files from the WRITE directory

' back to the root ...

CopyOrMoveFiles "A:\WRITE", "A:\", "WRI", "M"

' Moving the WRI files out of the WRITE directory should have cleared it, so

' it now can be removed with RmDir ...

RmDir "A:\WRITE"

' Free up the OS for a sec and ensure message is displayed ...

DoEvents

Print "WRITE directory has been cleared; files moved back to root."

Print "Done."

Refresh

Exit Sub

 

cmdReset_Click_Error:

MsgBox "The following error has occurred:" & vbNewLine _

& "Error # " & Err.Number & " - " & Err.Description, _

vbCritical, _

"File System Commands Demo - Error"

End Sub

 

After the cmdReset_Click event procedure has run, the form should look like this:

 

 

Download the VB project code for the example above here.

If you enjoyed this post, subscribe for updates (it's free)

Files handling

Good work,very descriptive,I learnt file system in 2 hour with this article.,hey can you also write an article upon how to store the required emails or phone no directory from the web to a file by using a loop, as there is also a browser control in vb.