Nested Folder Deletion with VB.Net

~OSD~ 2,131 Reputation points
2020-12-14T09:18:11.097+00:00

Hi,

I have following directory structure with static parent directory name and randomly created sub-directories. Where in each sub-directory, there are several folders with same names on all sub-directories.
47935-image.png

Is it supported to delete the specific folders with VB.Net (marked red in above screenshot) from all sub-folders (light green color), where the name of the parent directory (DemoRoot) is known but not the child directories (represented by SampleDir 1, SampleDir2, SampleDirN).

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,625 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 113.7K Reputation points
    2020-12-14T12:19:40.71+00:00

    In case of re-formulated problem, try this code:

    Dim names As String() = {"Dir_B", "Dir_C"}
    
    Dim root = "C:\MyFiles\DemoRoot"
    
    Dim directories = New DirectoryInfo(root).EnumerateDirectories().SelectMany(Function(x) x.EnumerateDirectories().Where(Function(d) Not names.Contains(d.Name, StringComparer.CurrentCultureIgnoreCase)))
    
    For Each d In directories
        Try
            d.Delete(recursive:=True)
        Catch exc As DirectoryNotFoundException
            ' ignore
        End Try
    Next
    
    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Viorel 113.7K Reputation points
    2020-12-14T09:40:52.437+00:00

    If the names Dir_B and Dir_C are known and are not present on other levels, then check this approach:

    Dim names As String() = {"Dir_B", "Dir_C"}
    
    Dim root = "C:\MyFiles\DemoRoot"
    
    For Each d In New DirectoryInfo(root).EnumerateDirectories()
        For Each n In names
            Dim f = New DirectoryInfo(Path.Combine(d.FullName, n))
            Try
                f.Delete(recursive:=True)
            Catch exc As DirectoryNotFoundException
                ' ignore
            End Try
        Next
    Next
    
    1 person found this answer helpful.
    0 comments No comments

  2. ~OSD~ 2,131 Reputation points
    2020-12-14T10:37:31.79+00:00

    Hi Viorel and thanks for reply.

    I regret to inform that I composed question with error, the directory structure remains same but actually the directories marked in red should remain while EVERYTHING else should be deleted. So in my case, Dir_B and Dir_C should be kept while all other directories should be deleted... possible?

    0 comments No comments