Udostępnij za pośrednictwem


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

Note

  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 DirectoryTextBoxTextBox 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 DirectoryTextBoxTextBox control displays the current location.

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

    The DirectoryTextBoxTextBox 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 BrowseButtonButton 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.

    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.

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

    The gathered information appears in the FilePickComboBoxComboBox, 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 DirectoryTextBoxTextBox.

Enabling a User to Select a File to Examine

Although the FilePickComboBoxComboBox 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.

    Dim thisFile = _
        My.Computer.FileSystem.GetFileInfo(CStr(FilePickComboBox.SelectedValue))
    

Enabling a User to Determine What Information to Gather

Now that files display in the FilePickComboBoxComboBox, 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).

    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.

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

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

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

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

    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.

    ' 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 FilePickComboBoxComboBox displays the text files.

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

My.Computer.FileSystem.CurrentDirectory Property

My.Computer.FileSystem.GetFileInfo Method

Change History

Date

History

Reason

September 2008

Updated and fixed sample code.

Customer feedback.