开发者

Populate a TreeView with a string directory

开发者 https://www.devze.com 2022-12-15 11:55 出处:网络
How to I populate a T开发者_开发技巧reeView with a directory as a string. I am using the FolderBrowserDialog to select a folder and the SelectedPath property to get the string path (i.e. C:\\Users\\Ad

How to I populate a T开发者_开发技巧reeView with a directory as a string. I am using the FolderBrowserDialog to select a folder and the SelectedPath property to get the string path (i.e. C:\Users\Admin).


Also, could I view files like this?


private void button1_Click(object sender, EventArgs e)
{
    FolderBrowserDialog dialog = new FolderBrowserDialog();
    if (dialog.ShowDialog() != DialogResult.OK) { return; }

    this.treeView1.Nodes.Add(TraverseDirectory(dialog.SelectedPath));

}


private TreeNode TraverseDirectory(string path)
{
    TreeNode result = new TreeNode(path);
    foreach (var subdirectory in Directory.GetDirectories(path))
    {
        result.Nodes.Add(TraverseDirectory(subdirectory));
    }

    return result;
}


Add the directory node to the treeview. Set the nodes name to the full path and text to the directory name.

Recursively add nodes to treeview. Use the System.IO DirectoryInfo and FileInfo collections to get the files and directories in each DirectoryInfo object. make the terminating condition of your recursive function the case where there are no child directories.


You could consider using controls such as FolderView and FileView from Shell MegaPack. They can be put inside your own forms instead of popping up a modal dialog.

0

精彩评论

暂无评论...
验证码 换一张
取 消