I have a string with directories and subdirectories that I need to format for a treeview. For that I'm trying to sort them into objects so I can know which parts are subfolders and which aren't. This is the code I have so far and it partially works but it gets a duplicate for every subfolder. All tips are helpful :D
This is my object
public class TreeViewModel
{
public string FolderName { get; set; }
public List<TreeViewModel> Children { get; set; }
}
And here's the rest of the code
string tmp = @ "A
B
C
A/B
A/B/C
A/B/C/D";
List <string> folders = new(tmp.Split('\n'));
List < TreeViewModel > model = new();
for (int i = 0; i < folders.Count; i++) {
string folderName = folders[i].Replace('\n', ' ').Trim();
List <TreeViewModel> subfolders = new();
for (int j = 0; j < folders.Count; j++) {
string subfolderName = folders[j].Replace('\n', ' ').Trim();
if (DirCompare(folderName, subfolderName)) {
subfolders.Add(new TreeViewModel {
FolderName = subfolderName
});
}
}
model.Add(new TreeViewModel {
FolderName = folderName,
Children = subfolders
});
}
foreach(var item in model) {
Debug.WriteLine("Folder: " + item.FolderName);
foreach(var item1 in item.Children) {
Debug.WriteLine("Subfolder: " + item1.FolderName);
}
}
}
bool DirCompare(string dir1, string dir2) {
DirectoryInfo di1 = new DirectoryInfo(dir1);
DirectoryInfo di2 = new DirectoryInfo(dir2);
bool isParent = false;
while (di2.Parent != null) {
if (di2.Parent.FullName == di1.FullName) {
isParent = true;
break;
} else di2 = di2.Parent;
}
return isParent;
}
As you can see in my output I get a duplicate for every subfolder
Folder: A
Subfolder: A/B
Subfolder: A/B/C
Subfolder: A/B/C/D
Folder: B
Folder: C
Folder: A/B
Subfolder: A/B/C
Subfolder: A/B/C/D
Folder: A/B/C
Subfolder: A/B/C/D
Folder: A/B/C/D