The choice between
while
and
do..while
is fairly simple: if you want to test the condition before executing the code, then use
while
; if you want to execute the code in the loop at least once before testing the condition, then use
do..while
.
The bigger problem is your choice of collection. By appending each parent node's text to a
List<string>
, you'll end up with the path in the wrong order. For example, if you have a tree structure of
C: ⇒ Users ⇒ Tim ⇒ Documents
, your final path will be:
"Documents\Tim\Users\C:"
.
You could replace the
Add
call with an
Insert
call:
path.Add(node.Text);
while (node.Parent != null)
{
path.Insert(0, node.Text);
node = node.Parent;
}
Or you could switch to using a
Stack<string>
, which iterates its values in the reverse order, producing the correct results:
var path = new Stack<string>();
var node = e.Node;
while (node != null)
{
path.Push(node.Text);
node = node.Parent;
}
string final = string.Join(Path.DirectorySeparatorChar, path);
Stack<T> Class (System.Collections.Generic) | Microsoft Learn[
^]