Export (0) Print
Expand All

Walkthrough: Manipulating Files and Folders in Visual Basic .NET

This walkthrough provides an introduction to the fundamentals of file I/O in Microsoft Visual Basic .NET. To illustrate the features, it creates a small application, 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.

Creating the Application

To begin the project, create a form from which users can select a directory, choose a file from the directory, and choose 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, 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

    chkAttributes

    Attributes

    True

    CheckBox Name

    Text

    Checked

    chkFileLength

    File Length

    True

    CheckBox Name

    Text

    Checked

    chkLastAccess

    Last Access Time

    True

    CheckBox Name

    Text

    Checked

    chkFirstLine

    Show First Line

    True

    CheckBox Name

    Text

    Checked

    chkSave

    Save Results

    False

Displaying the Current Directory

The FileExplorer application needs a starting point. Accordingly, the txtDirectory TextBox uses the CurDir 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 the txtDirectory TextBox displays the current location.
    txtDirectory.Text = CurDir()
    
  3. Run the program to verify that the CurDir function returns the correct path.

    The txtDirectory TextBox displays the current directory.

Changing Directories

Since a user may want to select files in a different directory, the application uses the ChDir function 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.
    ChDir(NewPath)
    

Verifying That a Valid Path Has Been Entered

The ChDir function requires the Path parameter, which may or may not include the drive letter. If the path does not specify the drive, ChDir uses the current drive. To avoid this potential source of confusion, the application incorporates a Try...Catch statement that catches such exceptions as well as exceptions that arise from the submission of a blank 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 ChDir(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 ChDir(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 <> "" Then
                MsgBox(ErrorMessage)
             End If
          End Try
    

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 Dir function, which returns a string representing the name of a file, directory, or folder matching a specified pattern. Since the Dir function returns only the first matching item, the application includes a Do Until...Loop to check each item. The following code added to the Submit button also restricts the types of files listed to .txt files.

Note   This process takes advantage of the fact that calling the Dir function without arguments leaves the previous matching pattern in place.

To display directory contents

  1. Insert Dim ContentItem As String at the beginning of the btnSubmit_Click event.
  2. After the line End Try insert:
       LstFilePick.Items.Clear()
       ' Only look at the .txt files.
       ContentItem = Dir("*.txt")
       If ContentItem = "" Then
          ErrorMessage = "No text files found."
          MsgBox(ErrorMessage)
       End If
       ' Iterate through the directory contents.
       Do Until ContentItem = ""
          ' Add it to the list.
          lstFilePick.Items.Add(ContentItem)
          ' Move to the next textfile.
          ContentItem = Dir()
       Loop
    

    The gathered information displays 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 MsgBox. In the second, the application creates a list in the ComboBox of all .txt files within the directory specified in the txtDirectory TextBox.

Enabling a User to Select a File to Examine

Although the lstFilePick ComboBox displays all files in a directory, a user probably wants to select and examine 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 Object
         thisFile = lstFilePick.SelectedItem
           
    

Enabling a user to determine what information to gather

Now that files display in the lstFilePick ComboBox, additional code enables a user to specify the reported information. For example, one user might want to merely know the date when the file was last accessed. Another user might want to know a file's size, too. A user checks or unchecks a series of CheckBoxes (chkAttributes, chkLastAccess, chkFileLength, chkFirstLine) to customize the results.

To display specific information

  1. Declare these variables at the beginning of the btnExamine_Click event after thisFile = lstFilePick.SelectedItems:
         Dim Attributes As FileAttribute
         Dim AttributeResult As String
         Dim StringAttributes As String
         Dim LastAccess As Date
         Dim Length As Long
         Dim FirstLine As String
         Dim FinalString As String
         Dim ErrorMessage As String
         Dim NewName As String
         NewName = Ctype(thisfile, String)
         If thisFile = Nothing Then
             MsgBox("You must select a file to examine.")
             Exit Sub
         End If
    

    The GetAttr function returns a member of the FileAttribute enumeration representing the attributes of a file, directory, or folder. The returned value is a sum of its enumeration values. To determine which attributes are set, use the And operator to perform a bitwise comparison between the value returned by GetAttr and the value of the file attribute you want.

    Note   Because the application inspects only text files, it is reasonable to ignore some values possibly returned by GetAttr, such as Directory, Hidden, and System. It should be noted that this example code will be incorrect for files with such attributes.
  2. Add the following code to the btnExamine_Click event after NewName = CType(thisFile, String)to enable a user to check the file's attributes.
         ' Check Attributes.
         Dim MultiAttribute as FileAttribute
         MultiAttribute = vbReadOnly Or vbArchive
         If chkAttributes.Checked = True Then
             Attributes = GetAttr(thisFile)
             If (Attributes And MultiAttribute) = MultiAttribute Then
                 AttributeResult = "ReadOnly and Archive"
             ElseIf (Attributes and vbReadOnly) = vbReadOnly Then
                 AttributeResult = "ReadOnly"
             ElseIf (Attributes and vbArchive) = vbArchive Then
                 AttributeResult = "Archive"
             Else
                 AttributeResult = "Normal"
             End If
         End If
    
  3. Add the following code to the end of the btnExamine_Click event.
         ' Check last access time.
         If chkLastAccess.Checked = True Then
              LastAccess = FileDateTime(NewName)
         End If
    

    The FileDateTime function 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.

  4. Add the following code to end of the btnExamine_Click event.
         ' Check Length.
         If chkFileLength.Checked = True Then
              Length = FileLen(NewName)
         End If
    

    The FileLen function, which determines the length of the file, returns a long value specifying the length of the file in bytes.

  5. Add the following code to the end of the btnExamine_Click event to enable a user to get the first line of the file.
         ' Check the first line.
         If chkFirstLine.Checked = True Then
              Try
                   FileOpen(1, NewName, OpenMode.Input)
                   FirstLine = (InputString(1, 80))
              Catch ex As Exception
                   ErrorMessage = "Something is wrong with the file you " & _
                   "are trying to examine. Make sure it is a text " & _
                   " file that is not empty or less than 80 characters."
                   MsgBox (ErrorMessage)
                   Exit Sub
              Finally
                   FileClose(1)
              End Try
    
         End If
    

Displaying the Results

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

To display the results

  1. At the beginning of the btnExamine_Click event, declare and initialize the following variables after Dim stringAttributes As String:
         stringAttributes = "The attributes of the file are: "
         Dim stringLastAccess As String
         stringLastAccess = "The file was last accessed on: "
         Dim stringLength As String
         stringLength = "The file's length, in bytes, is: "
         Dim strFirstLine As String
         strFirstLine = "The first 80 characters are: "
    
  2. At the end of the If statement that determines whether or not the chkAttributes CheckBox has been checked, add the following before the final End If.
         ' Add this to the results messagebox.
         FinalString = stringAttributes & AttributeResult & "." & vbCrLf
    
  3. At the end of the If statement that determines whether or not the chkLastAccess CheckBox has been checked, add the following before the final End If.
         ' Add to the messagebox.
         FinalString = FinalString & stringLastAccess & LastAccess & "." _
         & vbCrLf
    
  4. At the end of the If statement that determines whether or not the chkFileLength CheckBox has been checked, add the following before the final End If.
         ' Add to the messagebox.
         FinalString = FinalString & stringLength & CStr(Length) & "." _
         & vbCrLf
    
  5. At the end of the If statement that determines whether or not the chkFirstLine CheckBox has been checked, add the following before the final End If.
         ' Add to the messagebox.
         FinalString = FinalString & strFirstLine & Firstline & vbCrLf
    
  6. At the very end of the function, add the following before the final End Sub.
         If FinalString = "" Then
              MsgBox("No file attribute checkboxes selected.")
         Else
              MsgBox(FinalString)
         End If
    

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 to the end of the btnExamine_Click event.
         ' Check to see if results should be saved.
         If chkSave.Checked = True and finalstring <> "" Then
              ' FileOpen will create the file if it doesn't exist.
              FileOpen(1, "log.txt", OpenMode.Append)
              Writeline (1, finalString)
              FileClose(1)
         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." 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." The FileExplorer requires a text file whose length is at least 80 characters.
  2. Start the application.
  3. 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."

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

    The lstFilePick ComboBox displays the text files.

  5. Select test.txt in the lstFilePick ComboBox. Make sure all of the checkboxes are selected, and click Examine.

    The results form includes the file attributes, the last access date, the length, and the first 80 characters of the file.

  6. Select test2.txt in the lstFilePick ComboBox, deselect all checkboxes and click Examine.

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

  7. Select Attributes and Save Results and click Examine.

    The results form displays only the file's attributes.

  8. Close FileExplorer.

    Since you checked the Save Results option, FileExplorer generated 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

File Access with Visual Basic Run-Time Functions | Accessing Files with FileSystemObject | File Access Through the FileStream Class | System.IO Namespace | File Access Types and Functions | Visual Basic Language Walkthroughs | Choosing Among File I/O Options in Visual Basic .NET

Show:
© 2014 Microsoft