TreeView の TreeNode を、FullPath から取得する

TreeView の TreeNode には、FullPath というプロパティーが取得できます。

これは、例えば、

AAA
-- BBB
----CCC

FullPath を取得して、出力するコード

Debug.WriteLine(treeView1.SelectedNode.FullPath);

のような階層構造のとき、CCC の TreeNode.FullPath は、AAA\\BBB\\CCC のような文字列を返します。
この文字列をもとに、CCC を選択したいときに使用するコードです。

TreeNode n = treeView1.FindNodeByFullPath(PageTreeView.Nodes, fullPath);
treeView1.SelectedNode = n;

public TreeNode FindNodeByFullPath(TreeNodeCollection nodes, string fullPath)
{

    // fullPath の先頭が '\'の場合、先頭の '\'を除去
    if (fullPath.StartsWith("\\"))
    {
        fullPath = fullPath.Substring(1);
    }

    string[] pathParts = fullPath.Split('\\');
    TreeNode currentNode = null;

    // 全てのパスの要素を順に辿る
    foreach (string pathPart in pathParts)
    {
        bool nodeFound = false;
        // 現在のノードの子ノードを検索
        foreach (TreeNode node in nodes)
        {
            if (node.Text == pathPart)
            {
                currentNode = node;
                nodes = currentNode.Nodes;
                nodeFound = true;
                break;
            }
        }
        // ノードが見つからなければ、nullを返す
        if (!nodeFound)
        {
            return null;
        }
    }

    // 最後の要素で見つかったノードを選択して返す
    return currentNode;
}