演练:在 Visual Basic 中操作文件和目录Walkthrough: Manipulating Files and Directories in Visual Basic

本演练简单介绍 Visual Basic 中文件 I/O 的基础知识。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.

本演练使用 My.Computer.FileSystem Object 的成员,这些成员可从 Visual Basic 中获得。This walkthrough uses members of the My.Computer.FileSystem Object, which are available in Visual Basic. 有关更多信息,请参见FileSystemSee FileSystem for more information. 本演练结尾部分提供等效示例,该示例使用来自 System.IO 命名空间的类。At the end of the walkthrough, an equivalent example is provided that uses classes from the System.IO namespace.

备注

以下说明中的某些 Visual Studio 用户界面元素在计算机上出现的名称或位置可能会不同。Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. 这些元素取决于你所使用的 Visual Studio 版本和你所使用的设置。The Visual Studio edition that you have and the settings that you use determine these elements. 有关详细信息,请参阅个性化设置 IDEFor more information, see Personalizing the IDE.

创建项目To create the project

  1. 在“文件”菜单上,单击“新建项目”。 On the File menu, click New Project.

    此时将出现“新建项目” 对话框。The New Project dialog box appears.

  2. 在“已安装的模板”窗格中,展开“Visual Basic”,然后单击“Windows”。 In the Installed Templates pane, expand Visual Basic, and then click Windows. 在中间的“模板”窗格中,单击“Windows 窗体应用程序”。 In the Templates pane in the middle, click Windows Forms Application.

  3. 在“名称”框中,键入 FileExplorer 以设置项目名称,然后单击“确定”。In the Name box, type FileExplorer to set the project name, and then click OK.

    Visual Studio 会将项目添加到“解决方案资源管理器” 中,此时“Windows 窗体设计器”随即打开。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 PropertyProperty “值”Value
    ListBoxListBox NameName filesListBox
    ButtonButton NameName

    文本Text
    browseButton

    浏览Browse
    ButtonButton NameName

    文本Text
    examineButton

    检查Examine
    CheckBoxCheckBox NameName

    文本Text
    saveCheckBox

    保存结果Save Results
    FolderBrowserDialogFolderBrowserDialog NameName FolderBrowserDialog1

选择一个文件夹,并列出文件夹中的文件To select a folder, and list files in a folder

  1. 通过双击窗体上的控件,创建 browseButtonClick 事件处理程序。Create a Click event handler for browseButton by double-clicking the control on the form. 代码编辑器随即打开。The Code Editor opens.

  2. 将以下代码添加到 Click 事件处理程序中。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
    

    FolderBrowserDialog1.ShowDialog 调用将打开“浏览文件夹”对话框。 The FolderBrowserDialog1.ShowDialog call opens the Browse For Folder dialog box. 用户单击“确定”后 ,SelectedPath 属性作为参数发送给在下一步中添加的 ListFiles 方法。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. 添加以下 ListFiles 方法。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
    

    此代码首先会清除“ListBox”。 This code first clears the ListBox.

    GetFiles 方法然后检索字符串集合,一个字符串对应目录中的一个文件。The GetFiles method then retrieves a collection of strings, one for each file in the directory. GetFiles 方法接受一个搜索模式参数来检索与特定模式匹配的文件。The GetFiles method accepts a search pattern argument to retrieve files that match a particular pattern. 在此示例中,仅返回具有 .txt 扩展名的文件。In this example, only files that have the extension .txt are returned.

    通过 GetFiles 方法返回的字符串随后将添加到“ListBox”中。 The strings that are returned by the GetFiles method are then added to the ListBox.

  4. 运行该应用程序。Run the application. 单击“浏览” 按钮。Click the Browse button. 在“浏览文件夹”对话框中,浏览到包含 .txt 文件的文件夹,然后选择该文件夹,并单击“确定”。 In the Browse For Folder dialog box, browse to a folder that contains .txt files, and then select the folder and click OK.

    ListBox 包含所选文件夹中 .txt 文件的列表。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. 通过双击窗体上的控件,创建 examineButtonClick 事件处理程序。Create a Click event handler for examineButton by double-clicking the control on the form.

  2. 将以下代码添加到 Click 事件处理程序中。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)
    

    该代码验证是否在 ListBox 中选中某项。The code verifies that an item is selected in the ListBox. 然后,将从 ListBox 获取文件路径项。It then obtains the file path entry from the ListBox. FileExists 方法用于检查文件是否仍然存在。The FileExists method is used to check whether the file still exists.

    该文件路径作为参数发送给下一步中添加的 GetTextForOutput 方法。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. 该文件信息将出现在“MessageBox”中。 The file information appears in a MessageBox.

  3. 添加以下 GetTextForOutput 方法。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
    

    该代码使用 GetFileInfo 方法来获取文件参数。The code uses the GetFileInfo method to obtain file parameters. 文件参数添加到 StringBuilderThe file parameters are added to a StringBuilder.

    OpenTextFileReader 方法将文件内容读取到 StreamReaderThe OpenTextFileReader method reads the file contents into a StreamReader. 该内容的第一行是从 StreamReader 获取的,然后将添加到 StringBuilderThe first line of the contents is obtained from the StreamReader and is added to the StringBuilder.

  4. 运行该应用程序。Run the application. 单击“浏览”,然后浏览到包含 .txt 文件的文件夹。 Click Browse, and browse to a folder that contains .txt files. 单击“确定”。 Click OK.

    ListBox 中选择一个文件,然后单击“检查” 。Select a file in the ListBox, and then click Examine. MessageBox 显示文件信息。A MessageBox shows the file information.

  5. 停止运行该应用程序。Stop running the application.

添加日志项目To add a log entry

  1. 将以下代码添加到 examineButton_Click 事件处理程序末尾。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.

    WriteAllText 方法,其 append 参数设置为 True,用于创建日志条目。The WriteAllText method, with the append argument set to True, is used to create the log entry.

  2. 运行该应用程序。Run the application. 浏览到一个文本文件,在 ListBox 中选中它,选择“保存结果”复选框,然后再单击“检查”。 Browse to a text file, select it in the ListBox, select the Save Results check box, and then click Examine. 验证日志条目是否写入 log.txt 文件。Verify that the log entry is written to the log.txt file.

  3. 停止运行该应用程序。Stop running the application.

使用当前目录To use the current directory

  1. 通过双击窗体,创建 Form1_Load 的事件处理程序。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. 添加以下 SetEnabled 方法。Add the following SetEnabled method.

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

    SetEnabled 方法启用还是禁用控件是由是否选中 ListBox 中的项决定的。The SetEnabled method enables or disables controls depending on whether an item is selected in the ListBox.

  2. 通过双击窗体上的 ListBox 控件,创建 filesListBoxSelectedIndexChanged 事件处理程序。Create a SelectedIndexChanged event handler for filesListBox by double-clicking the ListBox control on the form.

  3. 在新的 filesListBox_SelectedIndexChanged 事件处理程序中添加对 SetEnabled 的调用。Add a call to SetEnabled in the new filesListBox_SelectedIndexChanged event handler.

  4. browseButton_Click 事件处理程序末尾添加对 SetEnabled 的调用。Add a call to SetEnabled at the end of the browseButton_Click event handler.

  5. Form1_Load 事件处理程序末尾添加对 SetEnabled 的调用。Add a call to SetEnabled at the end of the Form1_Load event handler.

  6. 运行该应用程序。Run the application. 如果在 ListBox 中未选中任何项,将禁用“保存结果”复选框和“检查”按钮。The Save Results check box and the Examine button are disabled if an item is not selected in the ListBox.

使用 My.Computer.FileSystem 的完整示例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

使用 System.IO 的完整示例Full example using System.IO

以下等效示例使用来自 System.IO 命名空间的类,而不使用 My.Computer.FileSystem 对象。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