Export (0) Print
Expand All

Walkthrough: Manipulating Files and Directories in Visual Basic 

This walkthrough provides an introduction to the fundamentals of file I/O in Microsoft Visual Basic 2005. To illustrate the features, it creates a small application, named FileExplorer, which examines text files within a directory and provides information such as attributes, last access time, and the first 80 characters of the file. It also includes an option that writes the information to a log file.

NoteNote

  The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is described in Help depending on your active settings or edition. This Help page was written with General Development Settings in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Visual Studio Settings.

To begin the project, create a form from which users can select a directory, select a file from the directory, and then select the information they want to retrieve about that file.

To create the project

  1. On the File menu, click New Project.

    The New Project dialog box appears.

  2. In the Project Types pane, click Visual Basic Projects, and then click Windows Application in the Templates pane.

  3. In the Name box, type FileExplorer to set the project name.

    Visual Studio adds the project to Solution Explorer, and the Windows Forms Designer opens.

  4. Add the controls in the following table to the form, and set the corresponding values for their properties.

    Object Properties Value

    TextBox

    Name

    Text

    txtDirectory

    Directory

    Button

    Name

    Text

    btnSubmit

    Submit

    Button

    Name

    Text

    btnExamine

    Examine

    ComboBox

    Name

    Text

    lstFilePick

    Select A File

    CheckBox

    Name

    Text

    Checked

    chkFileLength

    File Length

    True

    CheckBox

    Name

    Text

    Checked

    chkLastAccess

    Last Access Time

    True

    CheckBox

    Name

    Text

    Checked

    chkSave

    Save Results

    False

The FileExplorer application needs a starting point. Accordingly, the txtDirectory TextBox uses the My.Computer.FileSystem.CurrentDirectory function to return and display a string representing the current path.

To return the current directory

  1. Create an event handler for Form1_Load by double-clicking the form.

    The Code Editor opens.

  2. Add the following code so that the txtDirectory TextBox displays the current location.

    txtDirectory.Text = My.Computer.FileSystem.CurrentDirectory
    
    
  3. Run the program to verify that the correct path is returned.

    The txtDirectory TextBox displays the current directory.

Since a user may want to select files in a different directory, the application uses the same property to switch directories. To change to a different directory, a user enters a new path in the txtDirectory TextBox.

To change directories

  1. Create a click event handler for btnSubmit by double-clicking the control on the form.

    The Code Editor opens.

  2. Add the following code to the click event handler.

    Dim NewPath As String
    ' NewPath holds the path the user has entered.
    NewPath = txtDirectory.Text
    ' Change the location to NewPath.
    My.Computer.FileSystem.CurrentDirectory = NewPath
    
    

Use a Try...Catch statement to catch exceptions that arise from the submission of a blank or invalid path.

To ensure valid paths

  1. In the btnSubmit_Click event, after the code line Dim NewPath As String, add Dim ErrorMessage As String on a new line.

  2. Before the code line My.Computer.FileSystem.CurrentDirectory = NewPath add a Try statement on its own line as follows. If you hit return, the Code Editor will automatically insert Catch ex As Exception and End Try statements. Remove these; you will add your own in the next step.

    Try
    
    
  3. After the code line My.Computer.FileSystem.CurrentDirectory = NewPath, add the following.

        ' This checks to make sure the path is not blank.
    Catch ex As Exception When NewPath = ""
        ErrorMessage = "You must enter a path."
        ' This catches errors caused by a path that is not valid.
    Catch
        ErrorMessage = "You must enter a valid path.  If trying " & _
        "to access a different drive, remember to include the drive " & _
        "letter."
    Finally
        ' Display the error message only if one exists.
        If ErrorMessage <> Nothing Then
            MsgBox(ErrorMessage)
        End If
    End Try
    
    

To enable the application to display the contents of the current directory, you can use the My.Computer.FileSystem.GetFiles method, which returns a collection of strings representing the names of the files in the directory. You can use wildcards with GetFiles to select only files of a particular pattern. In this example, only files with the extension .txt are returned.

To display directory contents

  1. At the beginning of the btnSubmit_Click event, insert the following.

    Dim fileList As System.Collections.ObjectModel.ReadOnlyCollection(Of String).

  2. After the line End Try insert the following.

    fileList = My.Computer.FileSystem.GetFiles( _
        My.Computer.FileSystem.CurrentDirectory, _
        FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
    For Each foundFile As String In fileList
        lstFilePick.Items.Add(foundFile)
    Next
    
    

    The gathered information appears in the lstFilePick ComboBox, from which you can pick a specific file to examine.

Test the application by running it first on a directory that contains no .txt files and then on one that contains more than one .txt file. In the first instance, the application displays the appropriate error message. In the second, the application creates a list in the ComboBox of all .txt files within the directory specified in the txtDirectory TextBox.

Although the lstFilePick ComboBox displays all files in a directory, a user probably wants to select and examine a specific file.

To enable selection of a specific file

  • Create a click event handler for btnExamine_Click and add the following code to confirm a file's selection.

    Dim thisFile As System.IO.FileInfo
    thisFile = My.Computer.FileSystem.GetFileInfo(CStr(lstFilePick.SelectedItem))
    
    

Now that files display in the lstFilePick ComboBox, additional code enables a user to specify the reported information. For example, one user may merely want to know the date when the file was last accessed. Another user may also want to know a file's size. A user selects or clears check boxes (chkLastAccess, chkFileLength) to customize the results.

To display specific information

  1. Declare these variables at the beginning of the btnExamine_Click event after (lstFilePick.SelectedItem).

    Dim stringlength As String
    stringLength = "The file's length, in bytes, is: "
    Dim stringLastAccess As String
    stringLastAccess = "The file was last accessed on: "
    Dim LastAccess As Date
    Dim Length As Long
    Dim FirstLine As String = ""
    Dim FinalString As String = ""
    Dim NewName As String
    NewName = CType(lstFilePick.SelectedItem, String)
    
    If NewName = Nothing Then
        MsgBox("You must select a file to examine.")
        Exit Sub
    End If
    
    

    The My.Computer.FileSystem.GetFileInfo method returns a FileInfo object that can be queried to get information about a file.

  2. Add the following code to the end of the btnExamine_Click event.

    ' Check last access time.
    If chkLastAccess.Checked = True Then
        LastAccess = thisFile.LastAccessTime
    End If
    
    

The LastAccessTime property determines the last time the file was accessed. The returned Date value indicates the date and time when the file was created or last modified.

  1. Add the following code to the end of the btnExamine_Click event.

    ' Check Length.
    If chkFileLength.Checked = True Then
        Length = thisFile.Length
    End If
    
    

The Length property, which determines the length of the file, returns a Long value specifying the length of the file in bytes.

To complete the application's functionality, a MsgBox reports the gathered information.

To display the results

  1. At the end of the If statement that determines whether or not the chkLastAccess CheckBox has been selected, add the following before the final End If.

    ' Add to the messagebox.
    FinalString = FinalString & stringLastAccess & LastAccess & "." _
    & vbCrLf
    
    
  2. At the end of the If statement that determines whether or not the chkFileLength CheckBox has been selected, add the following before the final End If.

    ' Add to the messagebox.
    FinalString = FinalString & stringlength & CStr(Length) & "." _
    & vbCrLf
    
    
  3. At the end of the If statement that determines whether or not the chkFirstLine CheckBox has been selected, add the following before the final End If.

    ' Add to the messagebox.
    FinalString &= FirstLine & vbCrLf
    
    

A user may want to save the results of an examination of a file. Accordingly, add code that checks to see if a log file exists, creates one if necessary, and then writes the results to the log file.

To create a log file

  • Add the following to the end of the btnExamine_Click event.

    ' Check to see if results should be saved.
    If chkSave.Checked = True And FinalString <> "" Then
        My.Computer.FileSystem.WriteAllText("log.txt", FinalString, True)
    End If
    
    

To test your application

  1. In the directory of your choice, create a text file named test.txt with the following first line:

    "This is the first line of the first file. The FileExplorer application examines only text files."

  2. In the same directory, create a second text file named test2.txt with the following first line:

    "This is the first line of the second file. The FileExplorer application examines only text files."

  3. Start the application.

  4. Type an invalid path and click Submit.

    The following message appears: "You must enter a valid path. If trying to access a different drive, remember to include the drive letter."

  5. Type the path to the directory that stores test.txt and click Submit.

    The lstFilePick ComboBox displays the text files.

  6. Select test.txt in the lstFilePick ComboBox. Make sure all of the check boxes are selected, and then click Examine.

    The results form includes the last access date and the length.

  7. Select test2.txt in the lstFilePick ComboBox, clear all check boxes, and then click Examine.

    The following error message appears: "No file attribute checkboxes selected."

  8. Select Last Access and Save Results and click Examine.

    The results form displays only the last access time.

  9. Close FileExplorer.

    Because you checked the Save Results option, FileExplorer generates a log file named log.txt in the same directory as the text files.

To check the log

  • In the current directory, open log.txt and confirm that FileExplorer recorded the correct information.

Community Additions

ADD
Show:
© 2015 Microsoft