John

John

  • NA
  • 43
  • 34.1k

Opening Files in a Treeview

Jul 3 2013 4:00 AM
Hi All,

I'vjust finished me aking a program which displays all the files in a directory in a ListBox and lets me open them when selected. The problem I found with this was the files were hard to see what folder/subfolder they belonged too. So I'm trying to do the same thing with a treeview however I can't get the files to open from the subfolders.

Code so far:

  1. string dir = @"C:\Test\VideoTraining\";
  2. private void button1_Click(object sender, EventArgs e) // populate treeview
  3. {
  4. ListDirectory(treeView1, dir);
  5. }

  6. private void ListDirectory(TreeView treeview1, string dir)
  7. {
  8. treeView1.Nodes.Clear();
  9. var rootDirectoryInfo = new DirectoryInfo(dir);
  10. treeView1.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
  11. }

  12. private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
  13. {
  14. var directoryNode = new TreeNode(directoryInfo.Name);
  15. foreach (var directory in directoryInfo.GetDirectories())
  16. directoryNode.Nodes.Add(CreateDirectoryNode(directory));
  17. foreach (var file in directoryInfo.GetFiles())
  18. directoryNode.Nodes.Add(new TreeNode(file.Name));
  19. return directoryNode;
  20. }

  21. private void button2_Click(object sender, EventArgs e) // to open file
  22. {
  23. string name = treeView1.SelectedNode.ToString().Replace("TreeNode: ",string.Empty);
  24. MessageBox.Show(dir + "\\" + name);
  25. System.Diagnostics.Process.Start(dir + "\\" + name);
  26. }


Answers (10)