Walkthrough: Manipulating Files and Directories in Visual Basic

This walkthrough provides an introduction to the fundamentals of file I/O in Visual Basic. It describes how to create a small application that lists and examines text files in a directory. For each selected text file, the application provides file attributes and the first line of content. There is an option to write information to a log file.

This walkthrough uses members of the My.Computer.FileSystem Object, which are available in Visual Basic. See FileSystem for more information. At the end of the walkthrough, an equivalent example is provided that uses classes from the System.IO namespace.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To create the project

  1. On the File menu, click New Project.

    The New Project dialog box appears.

  2. In the Installed Templates pane, expand Visual Basic, and then click Windows. In the Templates pane in the middle, click Windows Forms Application.

  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.

    Control

    Property

    Value

    ListBox

    Name

    filesListBox

    Button

    Name

    Text

    browseButton

    Browse

    Button

    Name

    Text

    examineButton

    Examine

    CheckBox

    Name

    Text

    saveCheckBox

    Save Results

    FolderBrowserDialog

    Name

    FolderBrowserDialog1

To select a folder, and list files in a folder

  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() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
    End If
    

    The FolderBrowserDialog1.ShowDialog call opens the Browse For Folder dialog box. After the user clicks OK, the SelectedPath property is sent as an argument to the ListFiles method, which is added in the next step.

  3. Add the following ListFiles method.

    Private Sub ListFiles(ByVal folderPath As String)
        filesListBox.Items.Clear()
    
        Dim fileNames = My.Computer.FileSystem.GetFiles(
            folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
    
        For Each fileName As String In fileNames
            filesListBox.Items.Add(fileName)
        Next
    End Sub
    

    This code first clears the ListBox.

    The GetFiles method then retrieves a collection of strings, one for each file in the directory. The GetFiles method accepts a search pattern argument to retrieve files that match a particular pattern. In this example, only files that have the extension .txt are returned.

    The strings that are returned by the GetFiles method are then added to the ListBox.

  4. Run the application. Click the Browse button. In the Browse For Folder dialog box, browse to a folder that contains .txt files, and then select the folder and click OK.

    The ListBox contains a list of .txt files in the selected folder.

  5. Stop running the application.

To obtain attributes of a file, and content from a text file

  1. Create a Click event handler for examineButton by double-clicking the control on the form.

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

    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If
    
    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString
    
    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If My.Computer.FileSystem.FileExists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If
    
    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)
    
    ' Show the file information.
    MessageBox.Show(fileInfoText)
    

    The code verifies that an item is selected in the ListBox. It then obtains the file path entry from the ListBox. The FileExists method is used to check whether the file still exists.

    The file path is sent as an argument to the GetTextForOutput method, which is added in the next step. This method returns a string that contains file information. The file information appears in a MessageBox.

  3. Add the following GetTextForOutput method.

    Private Function GetTextForOutput(ByVal filePath As String) As String
        ' Verify that the file exists.
        If My.Computer.FileSystem.FileExists(filePath) = False Then
            Throw New Exception("File Not Found: " & filePath)
        End If
    
        ' Create a new StringBuilder, which is used
        ' to efficiently build strings.
        Dim sb As New System.Text.StringBuilder()
    
        ' Obtain file information.
        Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)
    
        ' Add file attributes.
        sb.Append("File: " & thisFile.FullName)
        sb.Append(vbCrLf)
        sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
        sb.Append(vbCrLf)
        sb.Append("Size: " & thisFile.Length.ToString & " bytes")
        sb.Append(vbCrLf)
    
        ' Open the text file.
        Dim sr As System.IO.StreamReader =
            My.Computer.FileSystem.OpenTextFileReader(filePath)
    
        ' Add the first line from the file.
        If sr.Peek() >= 0 Then
            sb.Append("First Line: " & sr.ReadLine())
        End If
        sr.Close()
    
        Return sb.ToString
    End Function
    

    The code uses the GetFileInfo method to obtain file parameters. The file parameters are added to a StringBuilder.

    The OpenTextFileReader method reads the file contents into a StreamReader. The first line of the contents is obtained from the StreamReader and is added to the StringBuilder.

  4. Run the application. Click Browse, and browse to a folder that contains .txt files. Click OK.

    Select a file in the ListBox, and then click Examine. A MessageBox shows the file information.

  5. Stop running the application.

To add a log entry

  1. Add the following code to the end of the examineButton_Click event handler.

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
        Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")
    
        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf
    
        ' Append text to the log file.
        My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
    End If
    

    The code sets the log file path to put the log file in the same directory as that of the selected file. The text of the log entry is set to the current date and time followed by the file information.

    The WriteAllText method, with the append argument set to True, is used to create the log entry.

  2. Run the application. Browse to a text file, select it in the ListBox, select the Save Results check box, and then click Examine. Verify that the log entry is written to the log.txt file.

  3. Stop running the application.

To use the current directory

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

  2. Add the following code to the event handler.

    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
    

    This code sets the default directory of the folder browser to the current directory.

  3. Run the application. When you click Browse the first time, the Browse For Folder dialog box opens to the current directory.

  4. Stop running the application.

To selectively enable controls

  1. Add the following SetEnabled method.

    Private Sub SetEnabled()
        Dim anySelected As Boolean =
            (filesListBox.SelectedItem IsNot Nothing)
    
        examineButton.Enabled = anySelected
        saveCheckBox.Enabled = anySelected
    End Sub
    

    The SetEnabled method enables or disables controls depending on whether an item is selected in the ListBox.

  2. Create a SelectedIndexChanged event handler for filesListBox by double-clicking the ListBox control on the form.

  3. Add a call to SetEnabled in the new filesListBox_SelectedIndexChanged event handler.

  4. Add a call to SetEnabled at the end of the browseButton_Click event handler.

  5. Add a call to SetEnabled at the end of the Form1_Load event handler.

  6. Run the application. The Save Results check box and the Examine button are disabled if an item is not selected in the ListBox.

Full example using My.Computer.FileSystem

Following is the complete example.


    ' This example uses members of the My.Computer.FileSystem
    ' object, which are available in Visual Basic.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Set the default directory of the folder browser to the current directory.
        FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory

        SetEnabled()
    End Sub

    Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            ' List files in the folder.
            ListFiles(FolderBrowserDialog1.SelectedPath)
        End If
        SetEnabled()
    End Sub

    Private Sub ListFiles(ByVal folderPath As String)
        filesListBox.Items.Clear()

        Dim fileNames = My.Computer.FileSystem.GetFiles(
            folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")

        For Each fileName As String In fileNames
            filesListBox.Items.Add(fileName)
        Next
    End Sub

    Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
        If filesListBox.SelectedItem Is Nothing Then
            MessageBox.Show("Please select a file.")
            Exit Sub
        End If

        ' Obtain the file path from the list box selection.
        Dim filePath = filesListBox.SelectedItem.ToString

        ' Verify that the file was not removed since the
        ' Browse button was clicked.
        If My.Computer.FileSystem.FileExists(filePath) = False Then
            MessageBox.Show("File Not Found: " & filePath)
            Exit Sub
        End If

        ' Obtain file information in a string.
        Dim fileInfoText As String = GetTextForOutput(filePath)

        ' Show the file information.
        MessageBox.Show(fileInfoText)

        If saveCheckBox.Checked = True Then
            ' Place the log file in the same folder as the examined file.
            Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
            Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")

            Dim logText As String = "Logged: " & Date.Now.ToString &
                vbCrLf & fileInfoText & vbCrLf & vbCrLf

            ' Append text to the log file.
            My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
        End If
    End Sub

    Private Function GetTextForOutput(ByVal filePath As String) As String
        ' Verify that the file exists.
        If My.Computer.FileSystem.FileExists(filePath) = False Then
            Throw New Exception("File Not Found: " & filePath)
        End If

        ' Create a new StringBuilder, which is used
        ' to efficiently build strings.
        Dim sb As New System.Text.StringBuilder()

        ' Obtain file information.
        Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)

        ' Add file attributes.
        sb.Append("File: " & thisFile.FullName)
        sb.Append(vbCrLf)
        sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
        sb.Append(vbCrLf)
        sb.Append("Size: " & thisFile.Length.ToString & " bytes")
        sb.Append(vbCrLf)

        ' Open the text file.
        Dim sr As System.IO.StreamReader =
            My.Computer.FileSystem.OpenTextFileReader(filePath)

        ' Add the first line from the file.
        If sr.Peek() >= 0 Then
            sb.Append("First Line: " & sr.ReadLine())
        End If
        sr.Close()

        Return sb.ToString
    End Function

    Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
        SetEnabled()
    End Sub

    Private Sub SetEnabled()
        Dim anySelected As Boolean =
            (filesListBox.SelectedItem IsNot Nothing)

        examineButton.Enabled = anySelected
        saveCheckBox.Enabled = anySelected
    End Sub

Full example using System.IO

The following equivalent example uses classes from the System.IO namespace instead of using My.Computer.FileSystem objects.


' This example uses classes from the System.IO namespace.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath =
        System.IO.Directory.GetCurrentDirectory()

    SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
        SetEnabled()
    End If
End Sub

Private Sub ListFiles(ByVal folderPath As String)
    filesListBox.Items.Clear()

    Dim fileNames As String() =
        System.IO.Directory.GetFiles(folderPath,
            "*.txt", System.IO.SearchOption.TopDirectoryOnly)

    For Each fileName As String In fileNames
        filesListBox.Items.Add(fileName)
    Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If

    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString

    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If System.IO.File.Exists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If

    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)

    ' Show the file information.
    MessageBox.Show(fileInfoText)

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String =
            System.IO.Path.GetDirectoryName(filePath)
        Dim logFilePath = System.IO.Path.Combine(logFolder, "log.txt")

        ' Append text to the log file.
        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf

        System.IO.File.AppendAllText(logFilePath, logText)
    End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String
    ' Verify that the file exists.
    If System.IO.File.Exists(filePath) = False Then
        Throw New Exception("File Not Found: " & filePath)
    End If

    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Obtain file information.
    Dim thisFile As New System.IO.FileInfo(filePath)

    ' Add file attributes.
    sb.Append("File: " & thisFile.FullName)
    sb.Append(vbCrLf)
    sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
    sb.Append(vbCrLf)
    sb.Append("Size: " & thisFile.Length.ToString & " bytes")
    sb.Append(vbCrLf)

    ' Open the text file.
    Dim sr As System.IO.StreamReader =
        System.IO.File.OpenText(filePath)

    ' Add the first line from the file.
    If sr.Peek() >= 0 Then
        sb.Append("First Line: " & sr.ReadLine())
    End If
    sr.Close()

    Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
    SetEnabled()
End Sub

Private Sub SetEnabled()
    Dim anySelected As Boolean =
        (filesListBox.SelectedItem IsNot Nothing)

    examineButton.Enabled = anySelected
    saveCheckBox.Enabled = anySelected
End Sub

See Also

Tasks

Walkthrough: Manipulating Files by Using .NET Framework Methods (Visual Basic)

Reference

System.IO

FileSystem

CurrentDirectory