Home > front end >  Create Folders with TreeView in WinForms
Create Folders with TreeView in WinForms

Time:09-08

I saw really many examples displaying exisiting folder structure with TreeView, but what I am trying to do is following ->

I have a standard folder structure in my C# WinForms with several folders and subfolders and a comboBox which display exisiting folders in my path.

The user should be able to choose a exisiting folder from my comboBox and just press a button to create every checked Item in my TreeView.

This is my existing Code:

    public Form1()
    {
        InitializeComponent();
        this.FormBorderStyle = FormBorderStyle.None;
        Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
        foreach (TreeNode tn in pathLorem.Nodes)
        {
            tn.Expand();
        }
        DirectoryInfo obj = new DirectoryInfo("F:\\");
        DirectoryInfo[] folders = obj.GetDirectories();
        loremDropDown.DataSource = folders;
    }

I don't beg for a finished code, I just need a tutorial or a exisiting StackOverflow post. I'm searching for 1 hour now.

enter image description here

CodePudding user response:

Based on your clarification, you need to create from the checked nodes tree directory structure in a given destination path.

Edit the constructor as follows...

public Form1()
{
    InitializeComponent();
    this.FormBorderStyle = FormBorderStyle.None;
    Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
    foreach (TreeNode tn in pathLorem.Nodes)
    {
        tn.Expand();
    }
    loremDropDown.DisplayMember = "Name";
    loremDropDown.ValueMember = "FullName";
    loremDropDown.DataSource = new DirectoryInfo("F:\\").GetDirectories();
}

Create a recursive method to get the checked nodes.

private IEnumerable<TreeNode> GetCheckedNodes(TreeNodeCollection nodeCol)
{
    foreach (TreeNode node in nodeCol)
    {
        if (node.Checked ||
            node.Nodes.Cast<TreeNode>().Any(n => n.Checked))
        {
            yield return node;
        }

        foreach (TreeNode childNode in GetCheckedNodes(node.Nodes))
        {
            if (childNode.Checked)
                yield return childNode;
        }
    }
}

To create the directories, Path.Combine the destination path and the TreeNode.FullPath and replace TreeView.PathSeparator with Path.DirectorySeparatorChar.

private void SomeButton_Click(object sender, EventArgs e)
{
    var destPath = loremDropDown.SelectedValue.ToString();
    var treeSep = pathLorem.PathSeparator;
    var dirSep = Path.DirectorySeparatorChar.ToString();

    foreach (var node in GetCheckedNodes(pathLorem.Nodes))
    {
        var sPath = Path.Combine(destPath, node.FullPath.Replace(treeSep, dirSep));
        Directory.CreateDirectory(sPath);
    }
}
  • Related