-
October 25th, 2010, 08:01 PM
#1
[RESOLVED] List Directory and Files inside a TreeView
I'm trying to code a TreeView that lists directory structure and files inside the TreeView, itself. There is no ListView. What is needed is a tree whose root is a directory instead of a drive. Everything I try either breaks the code, or doesn't produce the desired effect.
UPDATE 10/26/10: The following code has been corrected, and now works:
Code:
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
InitializeComponent();
PopulateTreeView();
}
private void PopulateTreeView()
{
TreeNode rootNode;
DirectoryInfo rootFolder = new DirectoryInfo(@"c:\TEST");
if (rootFolder.Exists)
{
rootNode = new TreeNode(rootFolder.Name);
rootNode.Tag = rootFolder;
GetDirectories(rootFolder.GetDirectories(), rootNode);
AddFiles(rootFolder, rootNode);
treeView1.Nodes.Add(rootNode);
}
}
private void GetDirectories(DirectoryInfo[] Dirs, TreeNode parentNode)
{
TreeNode dNode;
DirectoryInfo[] subDirs;
foreach (DirectoryInfo Di in Dirs)
{
dNode = new TreeNode(Di.Name, 0, 0);
dNode.Tag = Di;
dNode.ImageKey = "folder";
subDirs = Di.GetDirectories();
if (subDirs.Length != 0)
{
GetDirectories(subDirs, dNode);
}
parentNode.Nodes.Add(dNode);
AddFiles(Di, dNode);
}
}
private void AddFiles(DirectoryInfo Di, TreeNode dNode)
{
{
FileInfo[] fis = Di.GetFiles();
foreach (FileInfo fi in fis)
{
TreeNode fNode = new TreeNode(fi.Name);
fNode.ImageKey = "File.ico";
dNode.Nodes.Add(fNode);
}
}
}
}
}
Last edited by mbegley; October 26th, 2010 at 08:42 AM.
-
October 26th, 2010, 03:59 AM
#2
Re: List Directory and Files inside a TreeView
Your second version doesn't pick up the files in each directory. Add the following method:
void AddFiles(TreeNode dNode, DirectoryInfo Di)
{
FileInfo[] fis = Di.GetFiles();
foreach (FileInfo fi in fis)
{
TreeNode fNode = new TreeNode(fi.Name);
dNode.Nodes.Add(fNode);
}
}
Call that method for the root folder in PopulateTreeView() and each sub directory in GetDirectories() and you will get the display that you describe.
-
October 26th, 2010, 08:24 AM
#3
Re: List Directory and Files inside a TreeView
@ Millig... Your method works perfectly. I tried many times to write that method, but kept getting it wrong. (I was using DirectoryInfo[] as a formal parameter ). I updated the code snippet to show the correct method in case anyone else has the same problem. Thank you for your help.
Last edited by mbegley; October 26th, 2010 at 08:39 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|