演练:在 Visual Basic 中操作文件和目录

本演练介绍 Visual Basic 中的文件 I/O 基础知识。 它介绍如何创建一个小应用程序,用于列出和检查目录中的文本文件。 对于每个选定的文本文件,应用程序提供文件属性和第一行内容。 可以选择将信息写入日志文件。

本演练使用 My.Computer.FileSystem Object 的成员,这些成员可从 Visual Basic 中获得。 有关详细信息,请参阅 FileSystem。 在演练结束时,提供了一个等效的示例,该示例使用命名空间中的 System.IO 类。

注释

计算机可能会在以下说明中显示某些 Visual Studio 用户界面元素的不同名称或位置。 你拥有的 Visual Studio 版本以及所使用的设置决定了这些元素。 有关更多信息,请参阅 自定义 IDE

要创建项目

  1. 在“文件”菜单上,单击“新建项目”

    将显示“新建项目”对话框。

  2. “已安装的模板 ”窗格中,展开 Visual Basic,然后单击 “Windows”。 在中间的 “模板 ”窗格中,单击 “Windows 窗体应用程序”。

  3. 在“ 名称 ”框中,键入 FileExplorer 以设置项目名称,然后单击“ 确定”。

    Visual Studio 将项目添加到 解决方案资源管理器,Windows 窗体设计器随即打开。

  4. 将下表中的控件添加到窗体中,并为其属性设置相应的值。

    控制 资产 价值
    ListBox 名称 filesListBox
    按钮 名称

    文字
    browseButton

    浏览
    按钮 名称

    文字
    examineButton

    检视
    复选框 名称

    文字
    saveCheckBox

    保存结果
    FolderBrowserDialog 名称 FolderBrowserDialog1

选择文件夹,并列出文件夹中的文件

  1. 通过双击窗体上的控件,创建 ClickbrowseButton 事件处理程序。 此时会打开代码编辑器。

  2. 将以下代码添加到 Click 事件处理程序。

    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
    End If
    

    调用 FolderBrowserDialog1.ShowDialog 将打开 “浏览文件夹 ”对话框。 用户单击 “确定”后,该 SelectedPath 属性将作为参数 ListFiles 发送到该方法,该方法在下一步中添加。

  3. 添加以下 ListFiles 方法。

    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
    

    此代码首先清除 ListBox

    然后,该方法 GetFiles 检索字符串集合,其中一个用于目录中的每个文件。 该方法 GetFiles 接受搜索模式参数来检索与特定模式匹配的文件。 在此示例中,仅返回扩展名为 .txt 的文件。

    然后,方法返回 GetFiles 的字符串将添加到 ListBox

  4. 运行该应用程序。 单击“ 浏览 ”按钮。 在“ 浏览文件夹 ”对话框中,浏览到包含 .txt 文件的文件夹,然后选择该文件夹并单击“ 确定”。

    ListBox 包含选定文件夹中 .txt 文件列表。

  5. 停止运行应用程序。

获取文件的属性和文本文件中的内容

  1. 通过双击窗体上的控件,创建 ClickexamineButton 事件处理程序。

  2. 将以下代码添加到 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)
    

    代码验证在ListBox中是否已选中某个项。 然后,它从ListBox中获取文件路径条目。 该方法 FileExists 用于检查文件是否仍然存在。

    文件路径被作为参数发送到 GetTextForOutput 方法,该方法在下一步中添加。 此方法返回包含文件信息的字符串。 文件信息显示在 MessageBox 中。

  3. 添加以下 GetTextForOutput 方法。

    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
    

    代码使用 GetFileInfo 该方法获取文件参数。 文件参数添加到 StringBuilder

    OpenTextFileReader 方法将文件内容读入 StreamReader 中。 将 StreamReader 中内容的第一行获取出来,并将其添加到 StringBuilder 中。

  4. 运行该应用程序。 单击“ 浏览”,然后浏览到包含 .txt 文件的文件夹。 单击 “确定”

    ListBox 中选择一个文件,然后单击 检查MessageBox 显示文件信息。

  5. 停止运行应用程序。

添加日志项目

  1. 将以下代码添加到事件处理程序的 examineButton_Click 末尾。

    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
    

    代码将日志文件路径设置为将日志文件置于所选文件的同一目录中。 日志条目的文本设置为当前日期和时间,后跟文件信息。

    该方法 WriteAllText 的参数 append 设置为 True 用于创建日志条目。

  2. 运行该应用程序。 浏览到一个文本文件,在ListBox中选择它,选中“保存结果”复选框,然后单击“检查”。 验证日志条目是否已写入 log.txt 文件。

  3. 停止运行应用程序。

使用当前目录

  1. 通过双击窗体,创建 Form1_Load 的事件处理程序。

  2. 将以下代码添加到事件处理程序。

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

    此代码将文件夹浏览器的默认目录设置为当前目录。

  3. 运行该应用程序。 首次单击“ 浏览 ”时,“ 浏览文件夹 ”对话框将打开到当前目录。

  4. 停止运行应用程序。

有选择地启用控件

  1. 添加以下 SetEnabled 方法。

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

    方法 SetEnabled 根据是否在 ListBox 中选择了项目来启用或禁用控件。

  2. 通过双击窗体上的 SelectedIndexChanged 控件,创建 filesListBoxListBox 事件处理程序。

  3. 在新的 SetEnabled 事件处理程序中添加对 filesListBox_SelectedIndexChanged 的调用。

  4. SetEnabled 事件处理程序末尾添加对 browseButton_Click 的调用。

  5. SetEnabled 事件处理程序末尾添加对 Form1_Load 的调用。

  6. 运行该应用程序。 未在中选择项时,“保存结果”复选框和“ListBox”按钮将被禁用。

使用 My.Computer.FileSystem 的完整示例

下面是完整的示例。


' 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

使用 System.IO 的完整示例

下面的等效示例使用命名空间中的 System.IO 类,而不是使用 My.Computer.FileSystem 对象。


' 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

另请参阅