csharpcoder February 2016

Reconstruct Tree view from List<DirectoryInfo>

I have a function GetDirectories() which returns me the List of directory info : Now i need to reconstruct a tree view out of it , based on the its parent

Here is my function Getdirectories which return the List:

public List<DirectoryInfo> GetDirectories() 
    {
        DirectoryInfo di = new DirectoryInfo("D:\\python_code");
        folders.Clear();
        FullDirList(di, "*");
        return folders;
    }
 static List<DirectoryInfo> folders = new List<DirectoryInfo>(); // List that hold direcotries that cannot be accessed
 static void GetFullDirList(DirectoryInfo dir, string searchPattern)
    {
        try
        {
            foreach (FileInfo f in dir.GetFiles(searchPattern))
            {
                files.Add(f);
            }
        }
        catch
        {
        }

        foreach (DirectoryInfo d in dir.GetDirectories())
        {
            folders.Add(d);
            FullDirList(d, searchPattern);
        }

    }

I need something like this to be constructed from the List , which contain all the DirectoryInfo elements i.e it contains its parent info also .

Tree View of List<DirectoryInfo>

so far i am trying to get the elements whose parent are same and populate it to tree view and do it recursively : But i am not able to get the recursive function written through .

I know their other easier ways to do the same , but this is a recruitment of a big picture i am trying to draw . any help would be extremly appretiated .

Answers


rene February 2016

Assuming you have WinForms treeview you can use the key argument of the Find method on the Nodes collection to build up your hierarchy. You don't need recursion for that. Here is the Add method:

    void Add(DirectoryInfo di)
    {
        if (di.Parent != null )
        {
            // find our parent node
            var node = treeView1.Nodes.Find(di.Parent.FullName,true);
            if (node.Length == 0)
            {
                // not found, add it as root
                // FullName becomes the key
                treeView1.Nodes.Add(di.FullName, di.Name);
            }
            else
            {
                // not sure what is going on if node.Length > 1
                // anyway, add it to the first node, to be our parent
                node[0].Nodes.Add(di.FullName, di.Name);
            }
        }
        else
        {
            treeView1.Nodes.Add(di.FullName, di.Name);
        }
    } 

And a simple iterator will drive this method:

        var list = GetDirectories();
        foreach(var di in list)
        {
            Add(di);
        }

Post Status

Asked in February 2016
Viewed 3,055 times
Voted 12
Answered 1 times

Search




Leave an answer