递归删除文件和文件夹
Author: sebikul
要使用它,请调用Clean(),第一个参数是要清理的目录,如果要在清理完文件夹后删除根文件夹,则调用布尔值作为第二个参数。
Private Depth As Integer
Private Function Clean_Directories_From(Path As String) As Boolean
Dim Directory As String
Dim DirectoryList As String[]
Dim HadError As Boolean
If Not Exist(Path) Then Return False
DirectoryList = Dir(Path, Null, gb.Directory)
For Each Directory In DirectoryList
Directory = Path &/ Directory
Print Subst("Cleaning directory &1...", Directory),
If Exist(Directory) Then Try Rmdir Directory
If Not Error Then
Print ("Done")
Else If Error And Error.Code = 43 Then
Message.Warning(Subst(("Access forbiden. You can't access &1"), Directory))
'Print
Else If Error And Error.Code = 42 Or Error.Code = 70 Then
Print ("Directory has content")
Execute(Directory)
Print Subst("Deleting directory &1...", Directory),
Rmdir Directory
Print ("Done")
Else If Error And Error.Code = 49 Then ''symbolic links
Try Kill Directory
Else If Error Then
Message.Error(Error.Code & " - " & Error.Text)
HadError = True
Print ("Failed")
Endif
Next
If HadError Then Return False
Return True
End
Private Function Clean_Files_From(Path As String) As Boolean
Dim File As String
Dim FileList As String[]
Dim HadError As Boolean
If Not Exist(Path) Then Return False
FileList = Dir(Path, Null, gb.File)
For Each File In FileList
File = Path &/ File
Print Subst("Cleaning file &1...", File),
Try Kill File
If Error And Error.Code = 43 Then
Message.Warning(Subst(("Access forbiden. You can't access &1"), File))
'Print
Else If Error Then
Message.Error(Error.Code & " - " & Error.Text)
HadError = True
Print ("Failed")
Else
Print ("Done")
Endif
Next
If HadError Then Return False
Return True
End
Public Function Clean(Path As String, Optional CleanRoot As Boolean = True) As Boolean
Depth = 1
Return Execute(Path, CleanRoot)
End
Private Function Execute(Path As String, Optional CleanRoot As Boolean = True) As Boolean
If IsDir(Path) Then
Inc Depth
If Not Clean_Files_From(Path) Or Not Clean_Directories_From(Path) Then
If Not Main.PrintDebug Then Message.Error(Subst(("There was an error while cleaning the directory &1.\n You may check the logs for further information. If this is a bug, please report it."), Path))
Return False
Endif
Dec Depth
If CleanRoot And Depth = 1 Then
Print Subst("Deleting directory &1...", Path),
Try Rmdir Path
Print ("Done")
Endif
Return True
Else
Print Subst("Cleaning file &1...", Path),
Try Kill Path
If Error Then
Message.Error(Error.Code & " - " & Error.Text)
Print ("Failed")
Return False
Else
Print ("Done")
Return True
Endif
Endif
End
Examples
Dim Result as Boolean
Result = Clean("/home/user/dummy-folder", False)