Visual Basic Application Development
Walkthrough: Manipulating Files and Directories in Visual Basic

Updated: September 2008

This walkthrough provides an introduction to the fundamentals of file I/O in Microsoft Visual Basic 2005. To illustrate the features, it describes how to create 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.

Creating the Application

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, point to New and then click Project.

    The New Project dialog box appears.

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

  3. In the Name box, type FileExplorer to set the project name, and then click OK.

    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

    DirectoryTextBox

    Directory

    Button

    Name

    Text

    BrowseButton

    Browse

    Button

    Name

    Text

    ExamineButton

    Examine

    ComboBox

    Name

    Text

    FilePickComboBox

    Select a File

    CheckBox

    Name

    Text

    Checked

    FileLengthCheckBox

    File Length

    True

    CheckBox

    Name

    Text

    Checked

    LastAccessCheckBox

    Last Access Time

    True

    CheckBox

    Name

    Text

    Checked

    SaveCheckBox

    Save Results

    False

    FolderBrowserDialog

    Name

    FolderBrowserDialog1

Displaying the Current Directory

The FileExplorer application needs a starting point. Accordingly, the DirectoryTextBox TextBox control uses the My.Computer.FileSystem.CurrentDirectory function to return and display a string that represents 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 DirectoryTextBox TextBox control displays the current location.

    Visual Basic
    DirectoryTextBox.Text = My.Computer.FileSystem.CurrentDirectory
    FolderBrowserDialog1.SelectedPath = DirectoryTextBox.Text
    
  3. Run the program to verify that the correct path is returned.

    The DirectoryTextBox TextBox control displays the current directory.

Changing Directories

Because 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 clicks the BrowseButton Button control.

To change directories

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

    The Code Editor opens.

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

    Visual Basic
    If FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
        DirectoryTextBox.Text = FolderBrowserDialog1.SelectedPath
        My.Computer.FileSystem.CurrentDirectory = DirectoryTextBox.Text
    End If
    
Displaying the Contents of the Directory in a ComboBox

To enable the application to display the contents of the current directory, you can use the My.Computer.FileSystem.GetDirectoryInfo method, which returns a DirectoryInfo object for the specified directory. You can then call the GetFiles method of the DirectoryInfo object to retrieve a collection of FileInfo objects for each file in the directory. You can use wildcards with the GetFiles method to select only files of a particular pattern. In this example, only files with the extension .txt are returned.

To display directory contents

  • After the previously inserted code in the BrowseButton_Click event, insert the following code.

    Visual Basic
    FilePickComboBox.DataSource = _
        My.Computer.FileSystem.GetDirectoryInfo( _
        My.Computer.FileSystem.CurrentDirectory).GetFiles("*.txt")
    FilePickComboBox.DisplayMember = "Name"
    FilePickComboBox.ValueMember = "FullName"
    

    The gathered information appears in the FilePickComboBox 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 DirectoryTextBox TextBox.

Enabling a User to Select a File to Examine

Although the FilePickComboBox ComboBox control displays a list of 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 ExamineButton_Click and add the following code to confirm a file's selection.

    Visual Basic
    Dim thisFile = _
        My.Computer.FileSystem.GetFileInfo(CStr(FilePickComboBox.SelectedValue))
    
Enabling a User to Determine What Information to Gather

Now that files display in the FilePickComboBox 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 (LastAccessCheckBox, FileLengthCheckBox) to customize the results.

To display specific information

  1. Declare the following variables at the beginning of the ExamineButton_Click event, after (FilePickComboBox.SelectedItem).

    Visual Basic
    Dim stringlength = "The file's length, in bytes, is: "
    Dim stringLastAccess = "The file was last accessed on: "
    Dim lastAccess As Date
    Dim length As Long
    Dim finalString = ""
    

    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 ExamineButton_Click event.

    Visual Basic
    ' Check last access time.
    If LastAccessCheckBox.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 ExamineButton_Click event.

    Visual Basic
    ' Check length.
    If FileLengthCheckBox.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.

Displaying the Results

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 the LastAccessCheckBox CheckBox has been selected, add the following before the final End If.

    Visual Basic
    ' Add to the message box.
    finalString &= stringLastAccess & lastAccess & "." & vbCrLf
    
  2. At the end of the If statement that determines whether the FileLengthCheckBox CheckBox has been selected, add the following before the final End If.

    Visual Basic
    ' Add to the message box.
    finalString &= stringlength & CStr(length) & "." & vbCrLf
    
  3. To display the file information, add the following code before the final End Sub.

    Visual Basic
    MsgBox(finalString)
    
Saving the Results

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 code to the end of the ExamineButton_Click event.

    Visual Basic
    ' Check to see whether results should be saved.
    If SaveCheckBox.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 FilePickComboBox ComboBox displays the text files.

  6. Select test.txt in the FilePickComboBox 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 FilePickComboBox 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.

See Also

Reference

Change History

Date

History

Reason

September 2008

Updated and fixed sample code.

Customer feedback.

Tags :


Community Content

Claudio Gomes
Note in Walkthrough: Manipulating Files and Directories in Visual Basic tutorial.
There are a few improvements you can make to the code above.
  1. Clear the combo-box contents before loading it

    Why: This will avoid the combo-box growing exponentially when you click the <Submit> button several times.
    How: at the end of Private Sub btnSubmit_Click add the clear method as per below:

    Private Sub btnSubmit_Click  
    (...)
    lstFilePick.Items.Clear()
    For Each foundFile As String In fileList
    lstFilePick.Items.Add(foundFile)
    Next
    End Sub
  2. Set the location for the log file

    Why: Looks neater and forces you into a good programming practice for when you want to use FileSystem.WriteAllText method in the future. Not specifying the location can keep you guessing where the file has ended. This is usually the directory where the application is running from, and it will vary from each installation.
    How: An easy way is to place the file in the directory you're reading from as per below

    My.Computer.FileSystem.WriteAllText(txtDirectory.Text & "\log.txt", FinalString, True)

  3. Present the results on a message box


    Why: Might be easier and quicker if all you want to do is check the program results
    How: Swap the My.Computer.FileSystem.WriteAllText statement for a msgbox one as per below:

    MsgBox(FinalString, MsgBoxStyle.OkOnly)
  4. Use inline append operators

    Why: Although more a matter of personal preference and style, it's usually accepted that inline operators make a code easier to write and understand
    How: instead of ...

    FinalString = FinalString & stringLastAccess & LastAccess & "." & vbCrLf

    use

    FinalString &= stringLastAccess & LastAccess & "." & vbCrLf

Moiv
Exercise has not been updated to suit the revised code?
Step 4 of the final testing of the application talks about typing an invalid path and clicking submit. There is no where to type in a path and there is no submit button. The only way to select a path is through the FolderBrowserDialog and this cannot select a non existant directory.

I changed the log file line to be

My.Computer.FileSystem.WriteAllText( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments & _
"\FileExplorerLog.txt", finalstring, True)
This ensures it is always in the one location instead of spread all over the place.


Page view tracker