I was tasked creating a small(?) utility that walks a directory tree level by level and creating each level by calling a CreateDir(folder, parent) function that I have no access to its source code and creates a directory if it finds its parent. My question is similar to this question. Assuming I have this structure
A
-B
--D
---G
--E
-C
--F
I should create A first, then B and C, then D,E, and F and then G. Of course there is no limit to the depth.
I have created this method.
(IEnumerable<string>, IEnumerable<string>) GetAllFolders(string root)
{
var folders = Directory.EnumerateDirectories(root, "*", SearchOption.AllDirectories).Select(path => path.Replace(root, "").Substring(1));
var parents = folders.Select(path => path.Substring(0, (path.LastIndexOf(@"\") + 1) == 0 ? (path.LastIndexOf(@"\") + 1) : (path.LastIndexOf(@"\") ) ));
var listOfFolders = folders.ToList();
var listOfParents = parents.ToList();
return (listOfFolders, listOfParents);
}
And I try to create the structure using
foreach (var tuple in folders.Zip(parents, (x, y) => (x, y)))
{
if (tuple.y == String.Empty)
CreateDir(tuple.x,destination);
else
CreateDir(tuple.x, tuple.y);
}
where destination is a hardcoded path for the destination folder, folders and parents are the results of GetAllFolders.
I believe that I am overthinking it and that's why it is not working. Any simpler ideas?
