本演练介绍 Visual Basic 中的文件 I/O 基础知识。 它介绍如何创建一个小应用程序,用于列出和检查目录中的文本文件。 对于每个选定的文本文件,应用程序提供文件属性和第一行内容。 可以选择将信息写入日志文件。
本演练使用 My.Computer.FileSystem Object
的成员,这些成员可从 Visual Basic 中获得。 有关详细信息,请参阅 FileSystem。 在演练结束时,提供了一个等效的示例,该示例使用命名空间中的 System.IO 类。
注释
计算机可能会在以下说明中显示某些 Visual Studio 用户界面元素的不同名称或位置。 你拥有的 Visual Studio 版本以及所使用的设置决定了这些元素。 有关更多信息,请参阅 自定义 IDE。
要创建项目
在“文件”菜单上,单击“新建项目”。
将显示“新建项目”对话框。
在 “已安装的模板 ”窗格中,展开 Visual Basic,然后单击 “Windows”。 在中间的 “模板 ”窗格中,单击 “Windows 窗体应用程序”。
在“ 名称 ”框中,键入
FileExplorer
以设置项目名称,然后单击“ 确定”。Visual Studio 将项目添加到 解决方案资源管理器,Windows 窗体设计器随即打开。
将下表中的控件添加到窗体中,并为其属性设置相应的值。
控制 资产 价值 ListBox 名称 filesListBox
按钮 名称
文字browseButton
浏览按钮 名称
文字examineButton
检视复选框 名称
文字saveCheckBox
保存结果FolderBrowserDialog 名称 FolderBrowserDialog1
选择文件夹,并列出文件夹中的文件
通过双击窗体上的控件,创建
Click
的browseButton
事件处理程序。 此时会打开代码编辑器。将以下代码添加到
Click
事件处理程序。If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then ' List files in the folder. ListFiles(FolderBrowserDialog1.SelectedPath) End If
调用
FolderBrowserDialog1.ShowDialog
将打开 “浏览文件夹 ”对话框。 用户单击 “确定”后,该 SelectedPath 属性将作为参数ListFiles
发送到该方法,该方法在下一步中添加。添加以下
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。运行该应用程序。 单击“ 浏览 ”按钮。 在“ 浏览文件夹 ”对话框中,浏览到包含 .txt 文件的文件夹,然后选择该文件夹并单击“ 确定”。
ListBox
包含选定文件夹中 .txt 文件列表。停止运行应用程序。
获取文件的属性和文本文件中的内容
通过双击窗体上的控件,创建
Click
的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)
代码验证在
ListBox
中是否已选中某个项。 然后,它从ListBox
中获取文件路径条目。 该方法 FileExists 用于检查文件是否仍然存在。文件路径被作为参数发送到
GetTextForOutput
方法,该方法在下一步中添加。 此方法返回包含文件信息的字符串。 文件信息显示在 MessageBox 中。添加以下
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
中。运行该应用程序。 单击“ 浏览”,然后浏览到包含 .txt 文件的文件夹。 单击 “确定” 。
在
ListBox
中选择一个文件,然后单击 检查。MessageBox
显示文件信息。停止运行应用程序。
添加日志项目
将以下代码添加到事件处理程序的
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
用于创建日志条目。运行该应用程序。 浏览到一个文本文件,在
ListBox
中选择它,选中“保存结果”复选框,然后单击“检查”。 验证日志条目是否已写入log.txt
文件。停止运行应用程序。
使用当前目录
通过双击窗体,创建
Form1_Load
的事件处理程序。将以下代码添加到事件处理程序。
' Set the default directory of the folder browser to the current directory. FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
此代码将文件夹浏览器的默认目录设置为当前目录。
运行该应用程序。 首次单击“ 浏览 ”时,“ 浏览文件夹 ”对话框将打开到当前目录。
停止运行应用程序。
有选择地启用控件
添加以下
SetEnabled
方法。Private Sub SetEnabled() Dim anySelected As Boolean = (filesListBox.SelectedItem IsNot Nothing) examineButton.Enabled = anySelected saveCheckBox.Enabled = anySelected End Sub
方法
SetEnabled
根据是否在ListBox
中选择了项目来启用或禁用控件。通过双击窗体上的
SelectedIndexChanged
控件,创建filesListBox
的ListBox
事件处理程序。在新的
SetEnabled
事件处理程序中添加对filesListBox_SelectedIndexChanged
的调用。在
SetEnabled
事件处理程序末尾添加对browseButton_Click
的调用。在
SetEnabled
事件处理程序末尾添加对Form1_Load
的调用。运行该应用程序。 未在中选择项时,“保存结果”复选框和“
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