IntroductionIn this tips I have given, create directory and file detail as tree view in C#, I have seem so many questions in asked in forums, how to get the directory and file information in recursive manner.Hence I have created a simple screen with a treeview and label. Then compose the code to build directory tree. ImplementationI have created two methods for this operation. First one for build directory tree and second one for files trees. private void BuildTree(string directpath){DirectoryInfo dirInfo = new DirectoryInfo(directpath);FileSystemInfo[] collectionOfFAndD = dirInfo.GetFileSystemInfos();TreeNode parentnode = null;parentnode = new TreeNode(dirInfo.Name);parentnode.Tag = dirInfo.FullName;this.treeView1.Nodes.Add(parentnode);foreach (FileSystemInfo var in collectionOfFAndD){if (var.Attributes == FileAttributes.Directory){TreeNode node = new TreeNode(var.Name);node.Tag = var.FullName;parentnode.Nodes.Add(node);BuildFileTree(var.FullName, node);}else{TreeNode node = new TreeNode(var.Name);node.Tag = var.FullName;parentnode.Nodes.Add(node);}}}second method support add files to treeNode. private void BuildFileTree(string fileName, TreeNode parentnode){DirectoryInfo dirInfo = new DirectoryInfo(fileName);FileSystemInfo[] collectionOfFAndD = dirInfo.GetFileSystemInfos();foreach (FileSystemInfo var in collectionOfFAndD){if (var.Attributes == FileAttributes.Directory){TreeNode node = new TreeNode(var.Name);node.Tag = var.FullName;parentnode.Nodes.Add(node);BuildFileTree(var.FullName, node);}else{TreeNode node = new TreeNode(var.Name);node.Tag = var.FullName;parentnode.Nodes.Add(node);}}}The call parent method within the form load event to create treeview with directory private void Form1_Load(object sender, EventArgs e){BuildTree(@"C:\images");} now when you are click file node or directory node, you want to know full path and size of the file. so i have added code within after select event for treeview. private void treeView1_AfterSelect(object sender, TreeViewEventArgs e){FileInfo info = new FileInfo(e.Node.Tag.ToString());if (info.Attributes != FileAttributes.Directory){label1.Text = "Path:" + info.FullName + " \n Size:" + info.Length + " bytes";}else{label1.Text = "Path:" + info.FullName;}} When you are select any node in treeview you able to get path and size of the file. i hope this is help to you all. |