如何将文件夹结构加载到treeview中?

时间:2015-06-20 13:12:41

标签: c# treeview directory subdirectory

我想将目录结构加载到TreeView中。如果文件夹中有txt文件,则必须中断。不应显示子文件夹和文件。请帮我找一个算法

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 个答案:

答案 0 :(得分:0)

我这样解决了,

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;
            }
        }