任务 4 文件浏览器 1.运行界面
运行界面如图 6-4 所示。
118 Visual Basic.NET 程序设计案例教程
图 6-4 运行界面 2.功能
(1)根据选择的驱动器浏览当前驱动器内的目录。
(2)根据选择的目录浏览当前目录内的文件。
知识点 1 ListView 控件
Windows 窗 体 ListView 控 件 显 示 了 带 图 标 的 项 的 列 表 。 可 使 用 列 表 视 图 创 建 类 似 于 Windows 资源管理器右窗格的用户界面。该控件具有 4 种视图模式:LargeIcon、SmallIcon、List 和 Details。
大图标视图模式在项文本旁显示大图标;如果控件足够大,则项显示在多列中。小图标视图 模式除显示小图标外,其他方面与大图标视图模式相同。列表视图模式显示小图标,但总是显示 在单列中。Details 视图模式在多列中显示项。
ListView 控件的主要属性是 Items,该属性包含该控件显示的项。SelectedItems 属性包含控 件中当前选定项的集合。如果将 MultiSelect 属性设置为 true,则用户可选择多项,例如,同时将 若干项拖放到另一个控件中。如果将 CheckBoxes 属性设置为 true,ListView 控件可以显示这些 项旁的复选框。
Activation 属性可以确定用户激活列表中的某项时必须执行的操作类型:选项有 Standard、
OneClick 和 TwoClick。执行 OneClick 激活时,需要通过一次单击激活该项。执行 TwoClick 激 活时,要求用户通过双击激活该项。
知识点 2 DirectoryInfo 类
公开用于创建、移动和枚举目录和子目录的实例方法。无法继承此类。
1.DirectoryInfo 构造函数
在指定的路径中初始化 DirectoryInfo 类的新实例。
下面的实例使用此构造函数创建指定的目录及子目录,并演示包含子目录的目录不能被删除。
Imports System Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim di1 As DirectoryInfo = New DirectoryInfo("c:\MyDir") Dim di2 As DirectoryInfo = New DirectoryInfo("c:\MyDir\temp") Try
di1.Create() di2.Create()
Console.WriteLine("I am about to attempt to delete {0}.", di1.Name) di1.Delete()
Console.WriteLine("The Delete operation was successful, which was unexpected.") Catch e As Exception
Console.WriteLine("The Delete operation failed as expected.") End Try
End Sub End Class
2.DirectoryInfo.Exists 属性 获取指示目录是否存在的值。
属性值:如果目录存在,则为 true,否则为 false。
下面的示例演示了 Exists 属性在将源目录复制到目标目录时的用法。
Imports System Imports System.IO
Module Module1
Public Sub CopyDirectory(ByVal SourceDirectory As String, ByVal TargetDirectory As String) Dim source As DirectoryInfo = New DirectoryInfo(SourceDirectory)
Dim target As DirectoryInfo = New DirectoryInfo(TargetDirectory)
If (source.Exists = False) Then Return
End If
If (target.Exists = False) Then target.Create()
End If
Dim sourceFiles As FileInfo() = source.GetFiles() Dim i, j As Integer
For i = 0 To sourceFiles.Length - 1
File.Copy(sourceFiles(i).FullName, target.FullName + "\\" + sourceFiles(i).Name, True) Next i
Dim sourceDirectories As DirectoryInfo() = source.GetDirectories() For j = 0 To sourceDirectories.Length - 1
CopyDirectory(sourceDirectories(j).FullName, target.FullName + "\\" + sourceDirectories(j).Name) Next j
source = Nothing target = Nothing End Sub
Sub Main()
CopyDirectory("D:\\Tools", "D:\\NewTools") End Sub
End Module
3.DirectoryInfo.Name 属性 获取此 DirectoryInfo 实例的名称。
属性值:目录名称。
下面的实例仅显示当前 DirectoryInfo 实例的名称。
120 Visual Basic.NET 程序设计案例教程 Imports System
Imports System.IO
Class GetAName
Public Shared Sub Main()
Dim dir As New DirectoryInfo(".") Dim dirName As String = dir.Name
Console.WriteLine("DirectoryInfo name is {0}.", dirName) End Sub
End Class
4.DirectoryInfo.Parent 属性 获取指定子目录的父目录。
属 性 值 : 父 目 录 , 或 者 如 果 路 径 为 空 或 如 果 文 件 路 径 表 示 根 ( 如 “ \ ”、“ C: ” 或 *
“\\server\share”),则为空引用(在 Visual Basic 中为 Nothing)。
下面的实例演示了引用指定目录的父目录的方法。
Imports System Imports System.IO Public Class MoveToTest
Public Shared Sub Main()
Dim di As New DirectoryInfo("TempDir") If di.Exists = False Then
di.Create() End If
Dim dis As DirectoryInfo = di.CreateSubdirectory("SubDir") Dim parentDir As DirectoryInfo = dis.Parent
Console.WriteLine("The parent directory of '{0}' is '{1}'", dis.Name, parentDir.Name) di.Delete(True)
End Sub End Class
5.DirectoryInfo.Root 属性 获取路径的根部分。
属性值:代表路径的根的 DirectoryInfo 对象。
下面的实例演示了如何确定指定目录的根目录位置。
Imports System Imports System.IO Public Class MoveToTest
Public Shared Sub Main()
Dim di As New DirectoryInfo("TempDir") If di.Exists = False Then
di.Create() End If
Dim dis As DirectoryInfo = di.CreateSubdirectory("SubDir") Console.WriteLine("The root path of '{0}' is '{1}'", dis.Name, dis.Root) di.Delete(True)
End Sub End Class
6.DirectoryInfo.Create 方法
创建目录。如果目录已经存在,则此方法不执行任何操作。
下面的实例检查指定目录是否存在;如果该目录不存在,则创建此目录,然后删除该目录。
Imports System Imports System.IO Public Class Test
Public Shared Sub Main()
Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir") Try
If di.Exists Then
Console.WriteLine("That path exists already.") Return
End If
di.Create()
Console.WriteLine("The directory was created successfully.")
di.Delete()
Console.WriteLine("The directory was deleted successfully.")
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString()) End Try
End Sub End Class
7.DirectoryInfo.Delete 方法
如果此 DirectoryInfo 为空,则删除它。
下面的实例在试图删除一个非空目录时引发异常。
Imports System Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim di1 As DirectoryInfo = New DirectoryInfo("c:\MyDir") Try
di1.Create()
di1.CreateSubdirectory("temp")
Console.WriteLine("I am about to attempt to delete {0}", di1.Name) di1.Delete()
Console.WriteLine("The Delete operation was successful, which was unexpected.") Catch
Console.WriteLine("The Delete operation was unsuccessful, as expected.") End Try
End Sub End Class
8.DirectoryInfo.GetDirectories 方法
返回当前目录的子目录。如果没有子目录,则此方法只返回根目录。
返回值:DirectoryInfo 对象的数组。
下面的实例检索根目录下的所有目录并显示目录的名称。
Imports System Imports System.IO
Public Class GetDirectoriesTest Public Shared Sub Main()
Dim di As New DirectoryInfo("c:\")
Dim diArr As DirectoryInfo() = di.GetDirectories() Dim dri As DirectoryInfo
For Each dri In diArr
122 Visual Basic.NET 程序设计案例教程 Console.WriteLine(dri.Name) Next dri
End Sub End Class
9.DirectoryInfo.GetFiles 方法
返回当前目录的文件列表。如果 DirectoryInfo 中没有文件,则此方法返回一个空数组。
返回值:FileInfo 类型数组。
下面的实例从指定的目录检索文件。
Imports System Imports System.IO Public Class GetFilesTest Public Shared Sub Main()
Dim di As New DirectoryInfo("c:\") Dim fiArr As FileInfo() = di.GetFiles() Dim fri As FileInfo
For Each fri In fiArr
Console.WriteLine(fri.Name) Next fri
End Sub End Class
知识点 3 FileInfo 类
提供创建、复制、删除、移动和打开文件的实例方法,并且帮助创建 FileStream 对象。无法 继承此类。
1.FileInfo 构造函数
初始化 FileInfo 类的新实例,它作为文件路径的包装。
参数:fileName,新文件的完全限定名或相对文件名。
下面的实例使用此构造函数创建两个文件,并接着对其进行写入、读取、复制和删除操作。
Imports System Imports System.IO
Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim fi1 As FileInfo = New FileInfo(path)
If fi1.Exists = False Then
Dim sw As StreamWriter = fi1.CreateText() sw.WriteLine("Hello")
sw.WriteLine("And") sw.WriteLine("Welcome") sw.Flush()
sw.Close() End If
Dim sr As StreamReader = fi1.OpenText() Do While sr.Peek() >= 0
Console.WriteLine(sr.ReadLine()) Loop
Try
Dim path2 As String = path + "temp"
Dim fi2 As FileInfo = New FileInfo(path2) fi2.Delete()
fi1.CopyTo(path2)
Console.WriteLine("The directory '{0}' contains the following files and directories:", di.FullName) Dim info As FileSystemInfo
Dim fileName As String = "C:\autoexec.bat"
Dim fileInfo As New FileInfo(fileName) If Not fileInfo.Exists Then
Return End If
Console.WriteLine("{0} has a directoryName of {1}", fileName, fileInfo.DirectoryName)
4.FileInfo.Exists 属性 获取指示文件是否存在的值。
属性值:如果该文件存在,则为 true;如果该文件不存在或如果该文件是目录,则为 false。
下面的实例使用 Exists 属性确保文件在打开之前已经存在。
Function OpenDataFile(ByVal FileName As String) As Byte() If FileName Is Nothing OrElse FileName.Length = 0 Then Throw New ArgumentNullException("FileName") End If
Dim fInfo As New FileInfo(FileName) If Not fInfo.Exists Then
Throw New FileNotFoundException("The file was not found.", FileName) End If
Dim fStream As New FileStream(FileName, FileMode.Open) Dim buffer(fStream.Length) As Byte
fStream.Read(buffer, 0, Fix(fStream.Length)) Return buffer
124 Visual Basic.NET 程序设计案例教程 End Function
5.FileInfo.Length 属性
获取当前文件的大小。如果包含该文件的文件系统不支持此信息,则此属性值为空引用(在 Visual Basic 中为 Nothing)。
属性值:当前文件的大小。
下面的实例显示指定文件的大小。
Imports System Imports System.IO
Public Class FileLength Public Shared Sub Main()
Dim di As New DirectoryInfo("c:\") Dim fiArr As FileInfo() = di.GetFiles() Dim f As FileInfo
Console.WriteLine("The directory {0} contains the following files:", di.Name) For Each f In fiArr
Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length) Next f
End Sub End Class
6.FileInfo.Name 属性 获取文件名。
属性值:文件名。
下面的实例使用 Name 属性显示当前目录中的文件名。
Imports System Imports System.IO
Public Class NameTest Public Shared Sub Main()
Dim di As New DirectoryInfo(Environment.CurrentDirectory) Dim fi As FileInfo() = di.GetFiles()
Console.WriteLine("The following files exist in the current directory:") Dim fiTemp As FileInfo
For Each fiTemp In fi
Console.WriteLine(fiTemp.Name) Next fiTemp
End Sub End Class
7.FileInfo.Create 方法
创建文件。默认情况下,将向所有用户授予对新文件的完全读/写访问权限。
返回值:新文件。
下面的示例创建对文件的引用,然后使用 FileInfo.Create()在磁盘上创建此文件。
Imports System Imports System.IO
Public Class DeleteTest Public Shared Sub Main()
Dim fi As New FileInfo("temp.txt") Dim fs As FileStream = fi.Create() fs.Close()
fi.Delete() End Sub End Class
8.FileInfo.CopyTo 方法 将现有文件复制到新文件。
格式 1:
FileInfo.CopyTo(String) '将现有文件复制到新文件,不允许改写现有文件
Visual Basic(声明):
Public Function CopyTo ( _ destFileName As String _ ) As FileInfo
参数:destFileName 为要复制到的新文件的名称。
返回值:带有完全限定路径的新文件。
格式 2:
FileInfo.CopyTo(String, Boolean) '将现有文件复制到新文件,允许改写现有文件
Visual Basic(声明):
Public Function CopyTo ( _ destFileName As String, _ overwrite As Boolean _ ) As FileInfo
参数:destFileName 为要复制到的新文件的名称;overwrite 若为 true,则允许改写现有文 件;否则为 false。
返 回 值 : 新 文 件 , 或 者 如 果 overwrite 为 true,则改写现有文件。如果文件存在,且 overwrite 为 false,则会发生 IOException。
下面的实例演示了 CopyTo 方法的两个重载。
Imports System Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim path2 As String = path + "temp"
Dim fi As FileInfo = New FileInfo(path) Dim fi2 As FileInfo = New FileInfo(path2) Try
Dim fs As FileStream = fi.Create() fs.Close()
fi2.Delete() fi.CopyTo(path2)
Console.WriteLine("{0} was copied to {1}.", path, path2) fi.CopyTo(path2, True)
Console.WriteLine("The second Copy operation succeeded, which is expected.") Catch
Console.WriteLine("Double copying was not allowed, which is not expected.") End Try
End Sub End Class
9.FileInfo.Delete 方法
永久删除文件。如果文件不存在,则此方法不执行任何操作。
下面的实例说明 Delete 方法。
Imports System Imports System.IO Imports System.Text Public Class Test
Public Shared Sub Main()
126 Visual Basic.NET 程序设计案例教程
Dim path As String = "c:\temp\MyTest.txt"
Dim fi As FileInfo = New FileInfo(path) Try
Dim sw As StreamWriter = fi.CreateText() sw.Close()
Dim path2 As String = path + "temp"
Dim fi2 As FileInfo = New FileInfo(path2) fi2.Delete()
fi.CopyTo(path2)
Console.WriteLine("{0} was copied to {1}.", path, path2) fi2.Delete()
Console.WriteLine("{0} was successfully deleted.", path2) Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString()) End Try
End Sub End Class
知识点 4 DirListBox、DriveListBox 和 FileListBox 控件
建议使用 OpenFileDialog 和 SaveFileDialog 组件提供对文件系统的访问;但是,如果创建自 己的文件对话框,可以使用 Visual Basic 2005 在 Microsoft Visual Basic 兼容性运行库中提供的 DirListBox、DriveListBox 和 FileListBox 控件。
可以使用下列过程将 DirListBox、DriveListBox 或 FileListBox 添加到 Windows 应用程序 项目。
添加对兼容性库的引用:
(1)选择“项目”→“添加引用”命令。
(2)在弹出的“添加引用”对话框中,单击“.NET”选项卡。在“组件名称”列表中选择 Microsoft.VisualBasic.Compatibility,然后单击“确定”按钮,一个引用随即会添加到项目中。
将控件添加到工具箱的方法如下:
(1)选择“视图”→“工具箱”命令。
(2)展开“所有 Windows 窗体”部分。右击其标题栏,然后单击“选择项”。
(3)在“选择工具箱项”对话框中选中 DirListBox、DriveListBox 和 FileListBox 组件,然 后单击“确定”按钮,这些控件随即会添加到“工具箱”中,可以像任何其他 Windows 窗体控 件一样使用它们。
任务 4 解析
1.控件的属性(如表 6-12 所示)
表 6-12 控件属性说明
控件 Name 属性 Text 属性 其他属性
Form FormView 文件浏览器
DriveListBox DriveListBoxView DirListBox DirListBoxView
ListView ListViewFile 2.源代码
Public Class FormView
Private Sub DriveListBoxView_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DriveListBoxView.SelectedIndexChanged
Me.DirListBoxView.Path = Me.DriveListBoxView.Drive End Sub
Private Sub PopulateListView()
Me.ListViewFile.View = View.Details Dim header1, header2 As ColumnHeader header1 = New ColumnHeader header2 = New ColumnHeader header1.Text = "文件名称"
header1.TextAlign = HorizontalAlignment.Left header1.Width = 150
header2.Text = "位置"
header2.TextAlign = HorizontalAlignment.Left header2.Width = 550
Me.ListViewFile.Columns.Add(header1) Me.ListViewFile.Columns.Add(header2)
Dim dirinfo As New System.IO.DirectoryInfo(Me.DirListBoxView.Path) Dim file As System.IO.FileInfo
Dim files() As System.IO.FileInfo = dirinfo.GetFiles() Me.ListViewFile.Items.Clear()
If Not (files Is Nothing) Then For Each file In files
Dim item As New ListViewItem(file.Name) item.SubItems.Add(file.FullName) Me.ListViewFile.Items.Add(item) Next
End If End Sub
Private Sub DirListBoxView_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DirListBoxView.SelectedIndexChanged
Me.PopulateListView() End Sub
End Class