Files in Visual Basic

The first time we call Dir we must provide the directory as an argument, and it returns the first file in the directory. To get the rest of the files in the directory, we call Dir with no arguments and it returns the next file. To get all of the files, we loop until a null string is returned.

  1. Start a new project called directory.
  2. Add a listbox named lstFiles.
  3. Find a folder on your computer with some files that you can use.
  4. If necessary, create a folder call C;/mydata and copy a few files to it.
  5. Write the code in form load as shown below, changing the Dir statment to the folder on your computer with the files.
'Programmer: Janet Joy
'Show files in folder
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim S As String
        S = Dir("c:/mydata/") 'get first file in a folder
        While S <> ""
            S = Dir() 'get next file in same directory
        End While
    End Sub
End Class

When you run the program you will see a list of all the files in the folder:

If the directory contains sub folders, they are not returned. This will only return the top level files. If we want to return the names of all top level files, including directories, we can specify that with:

S = Dir("c:/clipart/", FileAttribute.Directory)

Because the Dir command has one setting for the whole program, we can not list all of the files in all of the subdirectories recursively, but we can use a stack to simulate recursion. (See linked file.) Dir can be used to test whether a particular file exists. For example S=Dir("C:/kids.jpg") will return a null string if the file does not exists. (There is no fileExists function.)

Other File Commands

Kill("C:/pictures/index.txt") 'deletes the specified file.
Kill("C:/pictures/*.txt") 'deletes all text files for the folder pictures. 

MkDir("C:\family") 'Create a new directory called family
RmDir("MYDIR") 'Removes the directory IF the directory is empty.

OldName = "C:\pictures\kids.jpg"
NewName = "C:\family\Jay and Debbie.jpg"
Rename(OldName, NewName)   ' Move and rename file.
Next: Select the target directory instead of coding it in to the program.

NEXT: Browse for Folder