Sam Stephenson
Sam Stephenson

Reputation: 5190

Change name of currently added Node

I am looking to change to name of the added node of a directory tree.

 private static TreeNode GetDirectoryNodes(string path)
    {
        var dir = new DirectoryInfo(path);
        var node = new TreeNode(path);
        //node.Nodes.Add("Windows");
        foreach (var directory in dir.GetDirectories())
        {
            node.Nodes.Add(GetDirectoryNodes(path + "\\" +directory.ToString()));
        }


        return node;
    }

This will give an output like

C:\Test1
|
|-C:\Test1\Test1
|  |-C:\Test1\Test1\Test1
|-C:\Test1\Test2

however I want to show

C:\Test1
|
|-Test1
|  |-Test1
|-Test2

I have foung that if I use

foreach (var directory in dir.GetDirectories())
        {
            node.Nodes.Add(directory.ToString());
        }

I will give the just the add path name but will not be recurrive for the sub directories output will be

 C:\Test1
|
|-Test1
|-Test2

So how do I get the name to change

Upvotes: 0

Views: 143

Answers (3)

JleruOHeP
JleruOHeP

Reputation: 10376

You can use DirectoryInfo.Name for nodes, it will give you short name without full path (and if you need you can store FullName in Tag). Like this:

var node = new TreeNode(dir.Name);

Upvotes: 1

Rawling
Rawling

Reputation: 50114

The line

var node = new TreeNode(path);

is where the text of each node is set (to the value of path).

Change this out for something like

var node = new TreeNode(path.Substring(path.LastIndexOf('\\') + 1));

Even better, don't do this through strings, but by passing DirectoryInfo objects. Then, rather than string-parsing out the directory name, you can just use the Name property:

private static TreeNode GetDirectoryNodes(DirectoryInfo dir)
{
    var node = new TreeNode(dir.Name);
    foreach (var childDir in dir.GetDirectories())
    {
        node.Nodes.Add(GetDirectoryNodes(childDir));
    }
    return node;
}

Upvotes: 1

Diego
Diego

Reputation: 36146

It seems like you want to strip out everything before the last '\' so why dont you just use the substring function FROM the index of the last '\' TO the end of the string.

Upvotes: 0

Related Questions