0

I was looking for a way to solve a simple problem and found this recursive solution: https://stackoverflow.com/a/674119/536607

Which is nice, but it assumes you have a fixed starting root and then builds the rest of the file structure under it.

I'm trying to come up with an algorithm that does essentially the same thing, except without that first hardcoded root. For example, I have the following files

Data/test.txt
Data/dir/results.txt
Another/image.jpg
file.dat

Would result in the following tree

Data
   test.txt
   dir
      results.txt
Another
   image.txt
file.dat

So it's almost like the other solution, except I remove the top root and then push everything back. But I guess you can't really do that easily (can you? It would be very convenient then)

Here is the algorithm I was thinking of

  • First, split the path as usual
  • Define a new method that will check whether the treeview contains a node with a key equal to the first part of the path (since we're rooted at directories)
  • If it exists, return that node. Else, create the node and return it
  • Now pass the node and the rest of the path parts into another method that will treat the node found in step 3 as the root and go from there.

Which sounds like it should work. Not too clear about the second step because what if the file was rooted wherever it was stored?

Community
  • 1
  • 1
MxLDevs
  • 17,348
  • 32
  • 112
  • 178

1 Answers1

0

Wrote up the algorithm described. Seems to work as expected. Not too sure about the files with no directories in the path though.

Anyone see an issue?

// start by getting the root
private void build_file_list(List<Entry> entries)
{
    TreeNode root;
    string[] pathbits;
    for (int i = 0; i < entries.Count(); i++)
    {
        pathbits = entries[i].name.Split(Path.DirectorySeparatorChar);
        root = get_root(pathbits[0]);
        add_path(root, pathbits);
    }
}

// returns existing node or creates a new one as needed
private TreeNode get_root(string key)
{
    if (explorer_view.Nodes.ContainsKey(key))
        return explorer_view.Nodes[key];
    else
        return explorer_view.Nodes.Add(key, key);
}

// now we have our root so we can start building the rest
private void add_path(TreeNode node, string[] pathbits)
{
    for (int i = 1; i < pathbits.Count(); i++)
        node = add_node(node, pathbits[i]);
}



// just recursively build nodes until end of file path
private TreeNode add_node(TreeNode node, string key)
{
    if (node.Nodes.ContainsKey(key))
        return node.Nodes[key];
    else
        return node.Nodes.Add(key, key);
}
MxLDevs
  • 17,348
  • 32
  • 112
  • 178