Click here to Skip to main content
16,021,226 members
Please Sign up or sign in to vote.
4.33/5 (2 votes)
See more:
I am making an explorer like app in C# windows form.So far what i have been able to do is that when i select the drive from combo box it displays the items in tree view but is not displaying it in the list view panel.What i basically want to make is an explorer that gets the drive from combo box and display all directories in tree view and when user selects the folder in tree view it displays the contents f that folder in the list view.I have to submit this today. Have gone through alomost every website but couldnt understand the right thing.My code is as follows:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace Assignment1b
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DriveInfo[] drives = DriveInfo.GetDrives();
            for (int i = 0; i <= drives.Length - 1; i++)
            {
                comboBox1.Items.Add(drives[i].Name);
                comboBox1.SelectedIndex = -1;
            }
        }

        private void gobtn_Click(object sender, EventArgs e)
        {
            ShowTreeViewItems(pathtb.Text);
            ShowDirectoryItems(pathtb.Text);
        }

        private void listView1_ItemActivate(object sender, EventArgs e)
        {
            pathtb.Text = pathtb.Text + listView1.SelectedItems[0].Text + "\\";
            ShowTreeViewItems(pathtb.Text);
            ShowDirectoryItems(pathtb.Text);
        }
        private void ShowTreeViewItems(string Path)
        {
            try
            {
                DirectoryInfo CurrDir = new DirectoryInfo(Path);
                DirectoryInfo[] SubDirs = CurrDir.GetDirectories();
                FileInfo[] Files = CurrDir.GetFiles();

                treeView1.Nodes.Clear();

                TreeNode parentNode = new TreeNode();
                parentNode.Text = Path;
                parentNode.ForeColor = Color.Black;
                parentNode.BackColor = Color.White;
                parentNode.ImageIndex = 2;
                parentNode.SelectedImageIndex = 2;
                treeView1.Nodes.Add(parentNode);

                foreach (DirectoryInfo dir in SubDirs)
                {
                    TreeNode childNode = new TreeNode();
                    childNode.Text = dir.Name;
                    childNode.ForeColor = Color.Black;
                    childNode.BackColor = Color.White;
                    childNode.ImageIndex = 2;
                    childNode.SelectedImageIndex = 2;
                    parentNode.Nodes.Add(childNode);
                    ////////////////////////////////////////////////////////
                    //TreeNode currentNode = new TreeNode();
                    //currentNode.Text = childNode.FullPath;
                    //currentNode.ForeColor = Color.Black;
                    //currentNode.BackColor = Color.White;
                    //currentNode.ImageIndex = 2;
                    //currentNode.SelectedImageIndex = 2;
                    //childNode.Nodes.Add(currentNode);

                }

                foreach (FileInfo file in Files)
                {
                    TreeNode childNode = new TreeNode();
                    childNode.Text = file.Name;
                    childNode.ForeColor = Color.Black;
                    childNode.BackColor = Color.White;
                    childNode.ImageIndex = 0;
                    childNode.SelectedImageIndex = 0;
                    parentNode.Nodes.Add(childNode);
                    ////////////////////////////////////////////////////
                    //TreeNode currentNode = new TreeNode();
                    //currentNode.Text = file.Name; ;
                    //currentNode.ForeColor = Color.Black;
                    //currentNode.BackColor = Color.White;
                    //currentNode.ImageIndex = 0;
                    //currentNode.SelectedImageIndex = 0;
                    //childNode.Nodes.Add(currentNode);
                }
                ShowDirectoryItems(Path);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message.ToString());
            }
        }

        private void ShowDirectoryItems(string Path)
        {
            DirectoryInfo CurrDir = new DirectoryInfo(Path);
            DirectoryInfo[] SubDirs = CurrDir.GetDirectories();
            FileInfo[] Files = CurrDir.GetFiles();

            DateTime dateModified;

            listView1.Items.Clear();

            listView1.BeginUpdate();

            foreach (DirectoryInfo dir in SubDirs)
            {
                ListViewItem item = new ListViewItem();
                item.Text = dir.Name;
                item.ImageIndex = 1;

                listView1.Items.Add(item);
            }

            foreach (FileInfo file in Files)
            {
                ListViewItem item = new ListViewItem();
                item.Text = file.Name;
                item.ImageIndex = 0;

                dateModified = File.GetLastWriteTime(file.FullName.ToString());
                item.SubItems.Add(dateModified.ToString());

                item.SubItems.Add((file.Length / 1024) + " KB");
                listView1.Items.Add(item);
            }

            listView1.EndUpdate();

        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            pathtb.Text = e.Node.FullPath.ToString();
            ShowTreeViewItems(e.Node.FullPath.ToString());
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            DirectoryInfo CurrDir = new DirectoryInfo(comboBox1.SelectedItem.ToString());
            DirectoryInfo[] SubDir = CurrDir.GetDirectories();
            FileInfo[] Files = CurrDir.GetFiles();

            try
            {
                foreach (DirectoryInfo dir in SubDir)
                {
                    TreeNode node = treeView1.Nodes.Add(dir.Name);
                    node.Nodes.Add("");
                }
                foreach (FileInfo file in Files)
                {
                    if (file.Extension.ToLower() == ".txt")
                    {
                        TreeNode node = treeView1.Nodes.Add(file.Name);
                    }
                }
                
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            try
            {
                TreeNode currentNode = e.Node;
                DirectoryInfo FolderPath = new DirectoryInfo(comboBox1.SelectedItem + currentNode.FullPath);
                DirectoryInfo[] Folder = FolderPath.GetDirectories();
                FileInfo[] Files = FolderPath.GetFiles();

                foreach (DirectoryInfo dir in Folder)
                {
                    TreeNode node = currentNode.Nodes.Add(dir.Name);
                    node.Nodes.Add(" ");
                }

                foreach (FileInfo file in Files)
                {
                    if ((file.Extension).ToLower() == ".txt")
                    {
                        TreeNode newNode = currentNode.Nodes.Add(file.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            comboBox1.Items.Add(e.Node.Text);
        }

        
    }
}


[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 16-Mar-14 1:15am
v3
Comments
OriginalGriff 16-Mar-14 7:16am    
So what part is giving you problems?
And what problems is it giving?
BillWoodruff 16-Mar-14 8:31am    
Your description of the problem, and your code, do not seem to be describing the same thing, to me. It appears you are showing individual files, as well as folders in the TreeView. Why not show only Directories and sub-Directories in the TreeView, and, when you get the Node AfterSelected Event, do the right thing to list the files in the ListView ?
Member 10377493 16-Mar-14 9:49am    
My form has a treeview a list view a combo box on top and a text box below a go button and a delete button...I want that when i select a drive the drive root node along with all the nodes gets displayed in the tree view as well as in list view i am trying to make an xplorer type app.how do i just get the directories in the tree view and all files and directories in list view
BillWoodruff 16-Mar-14 9:53am    
"the drive root node along with all the nodes gets displayed in the tree view" Does this mean you want any files at the root-level of a drive to show up in the TreeView as well as Directories ? That's not the Explorer UI model.
Member 10377493 16-Mar-14 10:06am    
i just want to make a simple explorer that display the directories of drives contained in the drive.Can u help with that?

1 solution

To be blunt: I don't understand your current design, and I don't have the time to put my head into your code. But, I would like to assist you, and I think the best way I can do that is to show you some working code I developed a few years ago.

1. Filling a TreeView recursively with every folder and sub-folder in a Drive:

a. requires: using System.IO;

b. assumes: a valid Drive Name in a string variable 'currentDrive

c. assumes a TreeView 'treeView1, and a ListView 'listView1.

d. the ListView has one column, and the View Property is set to 'Details
C#
// convenience variables
private string currentDrive = @"D://";

private DirectoryInfo currentDirectory;
private DirectoryInfo[] currentSubDirectories;

private TreeNode currentNode;

private void createTreeFromDrive()
{
    currentDirectory = new DirectoryInfo(currentDrive);
    currentSubDirectories = currentDirectory.GetDirectories();

    treeView1.Nodes.Clear();

    TreeNode currentNode = treeView1.Nodes.Add(currentDrive);

    fillTree(currentNode, currentSubDirectories);
}

// recursive code
private void fillTree(TreeNode currentNode, DirectoryInfo[] currentDirectories)
{
    foreach (var subDir in currentDirectories)
    {
        TreeNode subNode = currentNode.Nodes.Add(subDir.Name);

        // depending on the role/status of your User/App you may need more
        // or less work-arounds for no-go Directories
        if (subDir.Name.Contains("WindowsImageBackup")) continue;
        if (subDir.Name.Contains("System Volume Information")) continue;
        if (subDir.Name.Contains("Recycle")) continue;
        if (subDir.Name.Contains("Documents and Settings")) continue;
        if (subDir.Name.Contains("inetpub")) continue;

        DirectoryInfo[] subSubDirs = subDir.GetDirectories();
        
        if(subSubDirs.Length > 0) buildTree(subNode, subSubDirs);
    }
}
2. Given a click on a TreeNode, display the files in the associated Directory in a ListView:

a. assume you are using the default path separator string for a MS TreeView: the back-slash.
C#
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
    TreeNode currentNode = e.Node;

    listView1.Items.Clear();

    // requires .NET 4.0
    foreach (string file in Directory.EnumerateFiles(currentNode.FullPath, "*.*"))
    {
        listView1.Items.Add(file);
    }
}
Comments: this code is rather old, except for the one revision to use .NET 4.0: if I were to re-do it today, I'd probably change some things.
 
Share this answer
 
v2
Comments
Member 10377493 16-Mar-14 11:45am    
how do i populate list view with any selected item in the tree view?
BillWoodruff 16-Mar-14 12:22pm    
In the TreeView AfterSelect EventHandler in the code above you can see that the ListView Items are cleared, and then all the files in the path held in the 'FullPath property of the TreeNode are enumerated and inserted into the ListView's item collection.
Member 10377493 16-Mar-14 12:36pm    
I tried but its not working when i select any folder in tree view after this code it gives the following exception.

************* Exception Text **************
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\user\Documents\Visual Studio 2010\Projects\Assignment1b\Assignment1b\bin\Debug\libra'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileSystemEnumerableIterator`1.CommonInit()
at System.IO.FileSystemEnumerableIterator`1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler, Boolean checkHost)
at System.IO.Directory.EnumerateFiles(String path, String searchPattern)
at Assignment1b.Form1.treeView1_AfterSelect(Object sender, TreeViewEventArgs e) in C:\Users\user\Documents\Visual Studio 2010\Projects\Assignment1b\Assignment1b\Form1.cs:line 161
at System.Windows.Forms.TreeView.OnAfterSelect(TreeViewEventArgs e)
at System.Windows.Forms.TreeView.TvnSelected(NMTREEVIEW* nmtv)
at System.Windows.Forms.TreeView.WmNotify(Message& m)
at System.Windows.Forms.TreeView.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.18444 built by: FX451RTMGDR
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
Assignment1b
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///C:/Users/user/Documents/Visual%20Studio%202010/Projects/Assignment1b/Assignment1b/bin/Debug/Assignment1b.exe
----------------------------------------
System.Windows.Forms
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Configuration
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.18408 built by: FX451RTMGREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
<system.windows.forms jitdebugging="true">


When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.
Member 10377493 16-Mar-14 12:36pm    
I am going crazy with it and today it has to be submitted kindly help !!! ;(((((
BillWoodruff 16-Mar-14 12:48pm    
I truly wish I could help you, but, all I can say is that the code I posted works fine on my machine. If you are using some mix of your original code, and the code I posted, there could be some strange interaction which I'll never be able to know of.

If you are using the TreeView AfterSelect Event in the way I showed, then put a break-point on the foreach loop that enumerates the files in the Directory, and single-step through the code by pressing the F11 key (in Visual Studio).

The goal is to find the place where the error occurs, and then examine the state of all variables at that point. Usually, that's how you locate the source of the error.

good luck !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900