如果删除目录为空,则删除目录

时间:2014-02-20 22:40:35

标签: vb.net visual-studio-2012 directory.delete

以下Sub搜索某些文件夹并删除任何空文件夹(除非文件夹名为Bars或Backup)

sPath设置为c:\temp\working\,如果为空则应扫描和删除的文件夹是Working

的子目录

子工作完成了工作但是如果它到达所有子目录为空并且已被删除的点,则删除文件夹Working,这不是我需要发生的。

有关如何停止此操作的任何建议,或者我是否需要重新创建目录(如果它到达该阶段)(不理想)

  Public Sub DeleteEmptyFolders(ByVal sPath As String)

    Dim SubDirectories() As String = Directory.GetDirectories(sPath)
    For Each strDirectory As String In SubDirectories
        DeleteEmptyFolders(strDirectory)
    Next
    If Not (UCase(Path.GetDirectoryName(sPath)).Contains("BACKUP")) Or (UCase(Path.GetDirectoryName(sPath)).Contains("BARS")) Then
        If Directory.GetFiles(sPath).Length + Directory.GetDirectories(sPath).Length = 0 Then
            Directory.Delete(sPath)
            MsgBox("Deleting empty folder: " & sPath)
        End If
    End If
End Sub

由于

1 个答案:

答案 0 :(得分:1)

解决问题的第一种方法可能是传递起始根,如果是起始根,则不要删除目录

Public Sub DeleteEmptyFolders(ByVal sPath As String, ByVal sRoot As String)

    Dim SubDirectories() As String = Directory.GetDirectories(sPath )
    For Each strDirectory As String In SubDirectories
        DeleteEmptyFolders(strDirectory, sRoot)
    Next
    If Not (UCase(Path.GetDirectoryName(sPath)).Contains("BACKUP")) Or (UCase(Path.GetDirectoryName(sPath)).Contains("BARS")) Then
        If Directory.GetFiles(sPath).Length + Directory.GetDirectories(sPath).Length = 0 Then
            if sPath <> sRoot Then
                Directory.Delete(sPath)
                Console.WriteLine("Deleting empty folder: " & sPath)
            End If
        End If
    End If
End Sub

使用

进行通话
DeleteEmptyFolders("D:\temp", "D:\temp")