Question: How can I recursivly populate my treeview with multiple path values as strings from the registry into treeview nodes using C#?
What I would like to do: Recursivly Populate my treeView1 with string values from each registry value gathered in my list[] array also used for a listBox (listBox1) and ofcourse only adding values from the registry that is not null . I am very grateful for any help or input with this problem.
How I load my path into treeView1:
private void PopulateTreeView()
{
try
{
TreeNode rootNode;
NodeInfo nInfo;
string path = Global.GetStartUpPath();
DirectoryInfo info = new DirectoryInfo(path);
if (info.Exists)
{
rootNode = new TreeNode(info.Name, 3, 3);
rootNode.Name = info.Name;
nInfo = new NodeInfo(NodeInfo.Types.Root, info.FullName);
rootNode.Tag = nInfo;
GetDirectories(info, rootNode);
treeView1.Nodes.Add(rootNode);
treeView1.SelectedNode = rootNode;
}
}
How I set a path:
public static void setStartUpPath(string path)
{
//Open the registry key
RegistryKey rk1 = Registry.CurrentUser.OpenSubKey(@"Software", true);
//Create a subkey, if not exist
RegistryKey sk1 = rk1.CreateSubKey(@"Example\Test\Path");
sk1.SetValue("StartupPath", path);
sk1.Close();
_startUpPath = path;
}
And how I get it:
public static string GetStartUpPath()
{
if ( (_startUpPath != null) && (_startUpPath != string.Empty) )
return _startUpPath;
//Check registry
else
{
//Open the registry key
RegistryKey rk1 = Registry.CurrentUser.OpenSubKey(@"Software\Example\Test\Path", true);
if (rk1 == null)
return string.Empty;
_startUpPath = (string)rk1.GetValue("StartupPath");
rk1.Close();
return _startUpPath;
}
}
(If it helps) My method for getting the paths in to a listbox:
public static string[] GetPaths()
{
//Open the registry key
RegistryKey rk1 = Registry.CurrentUser.OpenSubKey(@"Software\Example\Test\Path\List", true);
if (rk1 == null)
return null;
string[] list = new string[rk1.ValueCount];
for (int i = 0; i < rk1.ValueCount; i++)
{
list[i] = rk1.GetValue(i.ToString()).ToString();
}
rk1.Close();
return list;
}
Solved it myself. For others coming here looking for an answer this is how I solved the treeview.
try
{
TreeNode rootNode;
NodeInfo nInfo;
string[] paths = Global.GetPaths();
for (int i = 0; i < paths.Length; i++)
{
string path = paths[i];
DirectoryInfo info = new DirectoryInfo(path);
if (info.Exists)
{
rootNode = new TreeNode(info.Name, 3, 3);
rootNode.Name = info.Name;
nInfo = new NodeInfo(NodeInfo.Types.Root, info.FullName);
rootNode.Tag = nInfo;
GetDirectories(info, rootNode);
treeView1.Nodes.Add(rootNode);
treeView1.SelectedNode = rootNode;
}
}
}
catch (Exception ex)
{
//.....
Logic.Log.write("ERROR PopulateTreeView -" + ex.Message);
}