How to load folder structure into treeview?

1k Views Asked by At

I want to Load Directory Structure Into TreeView. If there is a txt file in folder it must be break. Child folders and files should not shown. Please help me to find an algorithm

private void ListDirectory(TreeView treeView, string path)
{
    treeView.Nodes.Clear();
    var rootDirectoryInfo = new DirectoryInfo(path);
    treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
}

private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
    var directoryNode = new TreeNode(directoryInfo.Name);
    foreach (var directory in directoryInfo.GetDirectories())
    {
        if (directory.Name.EndsWith("txt"))
        {
            break;
        }
        else
        { 
            directoryNode.Nodes.Add(CreateDirectoryNode(directory)); 
        }
    }

    foreach (var file in directoryInfo.GetFiles())
    {
        if (directoryNode.Name.EndsWith("txt"))
        {
            directoryNode.Nodes.Add(new TreeNode(file.Name));
        }
    }

    return directoryNode;
}
1

There are 1 best solutions below

1
On

I solved it like that,

private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
        {
            var directoryNode = new TreeNode(directoryInfo.Name);

            try
            {
                int flag = 0;

                foreach (var file in directoryInfo.GetFiles())
                {
                    if (file.Name.EndsWith("txt"))
                    {
                        flag = 1;

                    }
                }
                if (flag == 0)
                {
                    foreach (var directory in directoryInfo.GetDirectories())
                    {

                        directoryNode.Nodes.Add(CreateDirectoryNode(directory));
                    }
                }

                return directoryNode;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }