Find common directory path

I created an extension to find common directory path from a list of paths.

When doing a search for such a tool, I came across this website:

I see that it is basically on the wish list, but I don’t know how to add this to there, so I am going to post the code here:

[code]Public Function Compare(extends txt1 as String, txt2 as String, FolderMode as Boolean = False, Sep1 as String = “”) as String
dim LongText as Text
dim ShortText as Text
if txt1.len > txt2.len then
LongText = txt1.ToText
ShortText = txt2.ToText
LongText = txt2.ToText
ShortText = txt1.ToText
end if
dim results as String = ShortText
Dim LongString as String = LongText
dim TempText as String
for each c as text in ShortText.Characters
if TempText = “” then
TempText = c
TempText = TempText + c
end if
if not LongString.Contains(TempText) then
results = TempText.Left(TempText.Len - 1)
exit for c
end if
next c

if FolderMode then
if not results.EndsWith(Sep1) then
dim txt() as String = results.Split(Sep1)
if not txt(txt.Ubound).EndsWith(Sep1) then
end if
results = Join(txt(), Sep1)
end if
end if

Return results

End Function

Public Function Contains(extends txt as String, st as String) as Boolean dim results as Boolean = False if txt.Lowercase.InStr(st.Lowercase) <> 0 then results = True Return results End Function

[code]Public Function GetCommonPath(extends FileList() as FolderItem, Sep1 as String = “”) as String
dim Results as String
for x as integer = 0 to FileList.Ubound
dim f as FolderItem = FileList(x)
if FolderExists(f) then
if not f.Directory then
f = f.Parent
end if
if Results = “” then
Results = f.NativePath
Results = Results.Compare(f.NativePath, True)
end if
end if
next x
Results = Results.LastCharacter(Sep1)

Return Results.Uppercase
End Function

Public Function FolderExists(f as FolderItem) as Boolean dim Results as Boolean = False if f <> nil then if f.Exists then Results = True end if end if Return Results End Function

Public Function gf(txt as String, DeleteIfExists as Boolean = False) as FolderItem dim Results as FolderItem = GetFolderItem(txt, FolderItem.PathTypeNative) if DeleteIfExists then if FolderExists(Results) then Results.Delete end if end if Return Results End Function

As you can see there are several functions that go into this, but it does work. Additionally, someone may have a better way of doing this, I am open to feedback as well.

FYI most of the Xojo code on RosettaCode is categorized under RealBasic.

There still isn’t code there for this and admittedly, I am still not sure this is the best approach, but it does work.

This is great. To add something to Rosetta code, create a free account, go to the Common Directory Path page and click the Edit link at the top. You can then add the code using one of the other code samples as a template.