简体   繁体   中英

My for statement isn't working properly

I have tried so much different iterations of the for loops and all of them dont work properly or work only halfway. So I cant figure it out. Heres my form:

在此处输入图片说明

So what its supposed to do is create a folder for each node in the treeview (Named FolderTV) when I click the Create folders button. What it currently does is only creates the New_Mod folder and the Data folder nothing else. I want it to create a folder for every node and subnode. For example it would create the New_Mod folder and then within that folder It will create the Data, Models, and Textures folder and within the Data folder it would create a Scripts folder.

Here's my code for that button:

private void button3_Click(object sender, EventArgs e)    
    {
        for (int i = 0; i <= FoldersTV.Nodes.Count; i++)
        {

            FoldersTV.SelectedNode = FoldersTV.TopNode;
            MessageBox.Show("Current Node: " + FoldersTV.SelectedNode.Text.ToString());
            Directory.CreateDirectory(SEAppdata + "\\" + FoldersTV.SelectedNode.Text.ToString());
            for (int x = 0; x <= FoldersTV.Nodes.Count; x++)
            {
                TreeNode nextNode = FoldersTV.SelectedNode.NextVisibleNode;
                MessageBox.Show("Next Node: " + nextNode.Text.ToString());
                Directory.CreateDirectory(SEAppdata + "\\" + FoldersTV.SelectedNode.Text.ToString() + "\\" + nextNode.Text.ToString());
                x++;
            }
            i++;
        }

    }

Try this (untested) recursive solution and try to understand it first ;)

private void CreateDirs(string path, IEnumerable<TreeNode> nodes) {
    foreach(var node in nodes) {
    //  string dir = path + "\\" + node.Text;
        string dir = Path.Combine(path, node.Text);
        Directory.CreateDirectory(dir);
        CreateDirs(dir, node.Nodes);
    }
}

private void button3_Click(object sender, EventArgs e) {
    CreateDirs(SEAppdata, FoldersTV.Nodes);
}

EDIT: Version with few debug printouts:

// using System.Diagnostics;
private void CreateDirs(string path, IEnumerable<TreeNode> nodes) {

//  iterate through each node (use the variable `node`!)
    foreach(var node in nodes) {
    //  combine the path with node.Text
        string dir = Path.Combine(path, node.Text);

    //  create the directory + debug printout
        Debug.WriteLine("CreateDirectory({0})", dir);
        Directory.CreateDirectory(dir);

    //  recursion (create sub-dirs for all sub-nodes)
        CreateDirs(dir, node.Nodes);
    }
}

See: System.Diagnostics.Debug.WriteLine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM