Thalia
Thalia

Reputation: 14605

vb.net find common parent directory

For a list of files, I am trying to determine the common parent directory. The files will not be in the same directory (tested that part)... I am trying

Dim myParentDirectory As String = Path.GetDirectoryName(list.Item(0))
Dim myCurrentDirectory As String
For Each file in list
  myCurrentDirectory = Path.GetDirectoryName(file)
  While myCurrentDirectory <> myParentDirectory And...  And myParentDirectory <> Nothing '(or <> to a top level directory like "c:")
   myParentDirectory = Directory.GetParent(myParentDirectory.ToString())
  End While
Next

The ... stands for "myCurrentDirectory is not subdirectory of myParentDirectory" but I haven't found anything that tests - only methods that list contents of a directory.

How can I get the common directory parent of two files (or directories) ?

Upvotes: 1

Views: 821

Answers (1)

Enigmativity
Enigmativity

Reputation: 117019

I've got a solution that works.

First up define a recursive function that gets you a list of all of the ancestor folders of a given folder:

Dim recurse As Func(Of DirectoryInfo, IEnumerable(Of string)) = Nothing
recurse = _
    Function (di)
        If di Is Nothing Then
            Return Enumerable.Empty(Of String)()
        Else
            Return Enumerable.Repeat(di.FullName, 1).Concat(recurse(di.Parent))
        End If
    End Function

Then it's just a matter of getting the intersection of two such sets of paths and return the longest one.

Like this:

Dim di1 As new DirectoryInfo("E:\James\Media\Podcasts\TEDTalks (video)")
Dim di2 As new DirectoryInfo("E:\James\Media\Music\A Clash of Kings")

Dim result =
    recurse(di1) _
        .Intersect(recurse(di2)) _
        .OrderByDescending(Function (x) x.Length) _
        .First()

Console.WriteLine(result)

The result is "E:\James\Media".

There might be prettier versions but it works.

Upvotes: 1

Related Questions