Search code examples
vb.netsubdirectory

How do I get the subdirectories in a folder without including the parent directory of said folder?


I know that IO.Directory.GetDirectories("X:/mydata/backup/stuff", "*", IO.SearchOption.AllDirectories) works for getting all directories, but I need to figure out how to not have the parent half attached to each string.

I need the output to be:

  • stuff/that/was/backed/up/file0.ext
  • stuff/that/was/backed/up/file1.ext
  • stuff/that/was/backed/up/file3.ext

Instead of:

  • X:/mydata/backup/stuff/that/was/backed/up/file0
  • etc.

The path can be anything, so I can't use a hard-coded solution either, like using Split(path, "/", 2) in the Application.StartupPath directory (which I currently use).


Solution

  • after much hair pulling and completely unhelpful comments, I have found a solution:

    Dim unitstring As String() = Split(TextBox2.Text, "\") 'separate directory names
    Dim unitcount As Integer = Array.LastIndexOf(unitstring, Path.GetFileName(TextBox2.Text)) + 2 'get how far in the directory we are from the root. 
    Dim paths As New List(Of String) 'list to hold results
    For Each x In IO.Directory.GetDirectories(TextBox2.Text, "*", SearchOption.AllDirectories) 'loop through all directories to get them in the format needed
        Dim pathsplit As String() = Split(x, "\", unitcount) 'split from parent
        paths.Add(pathsplit(unitcount - 1)) 'the last item in the array is what is needed.
    Next
    

    if anyone else needs code like this, feel free to use it.