上一节讲到了使用DirectoryInfo属性获取目录信息,本节讲一下有关DirectoryInfo的几个重要方法:创建、删除、移动
Private Sub btnCreateFolder_Click(sender As Object,e As EventArgs) Handles btnCreateFolder.Click Dim di As New DirectoryInfo("d:\aa") If di.Exists Then txtFolderInfo.Text = "文件夹已经存在" Exit Sub End If di.Create() txtFolderInfo.Text = "文件夹已经创建" End Sub
其中判断了目录是否已经存在,如果已经存在那么退出。
Private Sub btnDelFolder_Click(sender As Object,e As EventArgs) Handles btnDelFolder.Click Dim di As New DirectoryInfo("d:\aa") If di.Exists Then Try di.Delete() txtFolderInfo.Text = "文件夹已经删除" Catch ex As Exception txtFolderInfo.Text = "删除文件夹时发生错误," & ex.Message End Try Else txtFolderInfo.Text = "文件夹不存在" End If End Sub
实际上这个代码存在一些问题,如果需要删除的目录中包含子目录或者文件,那么会产生错误。
可以使用重载的Delete()方法完成对包含有子目录或者文件的目录的删除:
Private Sub btnDelFolder2_Click(sender As Object,e As EventArgs) Handles btnDelFolder2.Click Dim di As New DirectoryInfo("d:\aa") If di.Exists Then Try di.Delete(True) txtFolderInfo.Text = "文件夹已经删除" Catch ex As Exception txtFolderInfo.Text = "删除文件夹时发生错误," & ex.Message End Try Else txtFolderInfo.Text = "文件夹不存在" End If End Sub
代码中,di.Delete(True),参数True指明了要删除该目录中的子目录和文件。
Private Sub btnMoveFolder_Click(sender As Object,e As EventArgs) Handles btnMoveFolder.Click Dim di As New DirectoryInfo("d:\aa") If di.Exists Then Try di.MoveTo("d:\dd") txtFolderInfo.Text = "文件夹已经移动完毕" Catch ex As Exception txtFolderInfo.Text = "移动文件夹时发生错误," & ex.Message End Try Else txtFolderInfo.Text = "文件夹不存在" End If End Sub
di.MoveTo("d:\dd")
为
di.MoveTo("c:\dd")
会产生错误:
学习更多vb.net知识,请参看 vb.net 教程 目录
原文链接:https://www.f2er.com/vb/256556.html