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

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

本演练使用 My.Computer.FileSystem Object 的成员,Visual Basic 中提供了这些成员。 有关更多信息,请参见 FileSystem。 在本演练的最后提供了一个等效示例,该示例使用来自 System.IO 命名空间的类。

备注

对于在以下说明中使用的某些 Visual Studio 用户界面元素,您的计算机可能会显示不同的名称或位置。这些元素取决于您所使用的 Visual Studio 版本和您所使用的设置。有关更多信息,请参见 Visual Studio 设置

创建项目

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

    此时将出现**“新建项目”**对话框。

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

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

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

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

    控件

    属性

    ListBox

    名称

    filesListBox

    Button

    名称

    Text

    browseButton

    浏览

    Button

    名称

    Text

    examineButton

    Examine

    CheckBox

    名称

    Text

    saveCheckBox

    Save Results

    FolderBrowserDialog

    名称

    FolderBrowserDialog1

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

  1. 通过双击窗体上的控件,为 browseButton 创建一个 Click 事件处理程序。 代码编辑器打开。

  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. 通过双击窗体上的控件,为 examineButton 创建一个 Click 事件处理程序。

  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. 通过双击窗体上的 ListBox 控件,为 filesListBox 创建一个 SelectedIndexChanged 事件处理程序。

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

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

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

  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

请参见

任务

演练:使用 .NET Framework 方法操作文件 (Visual Basic)

参考

System.IO

FileSystem

CurrentDirectory