Monday, October 25, 2021

[VB.net][Example] Safely delete directories

This project required delete folders with thread-safe, support you added a list of directory-path into pendingDelteDirectories before you call removeDirectories() function.


Class Test

Private pendingDelteDirectories As List(Of String) = New List(Of String)

Private sortLock As New Object

Private removeDirectoryLock As New Object


Public Sub removeDirectories()

  Dim currentHandleDir As String = String.Empty

  SyncLock sortLock

    pendingDeleteDirectories.Sort(Function(x,y) y.Length.CompareTo(x.Length))

    If (pendingDeleteDirectory).Count > 0 AndAlso getFolderSize(pendingDeleteDirectories) > 0) Then Return

  End


  Try

    SyncLock removeDirectoryLock 

      For Each dir As String in pendingDeleteDirectories

        If Directory.Exists(dir) Then

          currentHandler = dir

          'Delete after checked empty

          If(Directory.Exists(dir) AndAlso _

             getFolderSize(dir) = 0 AndAlso _ 

             Directory.GetDirectories(dir,"*", SearchOption.AllDirectories).Length = 0) Then

               Directory.Delete(dir, False)

          End If

        End If

      Next 

      pendingDeleteDirectories = New List(Of String)

    End SyncLock

  Catch ex As Exception

    Debug.WriteLine(ex.toString())

  End Try

End Sub


End Class

No comments :

Post a Comment