Solved

Building tree-view similar to file explorer... c#

Posted on 2014-12-25
4
754 Views
Last Modified: 2014-12-25
I am following the link below to create file/folder tree-view similar to file explore:
http://msdn.microsoft.com/en-us/library/ms171645%28v=vs.80%29.aspx

For now, I have included only basic exception handling. After I run it, nothing shows up (no folders, no subfolders, no files) in on the form.

Question: How can I make this code work?

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;

namespace FilesAndFolderInTreeView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            PopulateTreeView();
            this.treeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //https://www.youtube.com/watch?v=xSgsEMVy7TU&list=PL1fDI09J3Pb0v32kA9RZyqr6k1gnBnfJq&index=1
            //http://msdn.microsoft.com/en-us/library/ms171645(v=vs.80).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
        }

        private void PopulateTreeView()
        {
            try
            {
                TreeNode rootNode;

                DirectoryInfo info = new DirectoryInfo(@"C:\Users\Public\Documents\UntypeDatasetSample");
                if (info.Exists)
                {
                    rootNode = new TreeNode(info.Name);
                    rootNode.Tag = info;
                    GetDirectories(info.GetDirectories(), rootNode);
                    treeView1.Nodes.Add(rootNode);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("1" + ex.Message);
            }


        }

        private void GetDirectories(DirectoryInfo[] subDirs,
            TreeNode nodeToAddTo)
        {
           
           try
           {
 
            TreeNode aNode;
            DirectoryInfo[] subSubDirs;
            foreach (DirectoryInfo subDir in subDirs)
            {
                aNode = new TreeNode(subDir.Name, 0, 0);
                aNode.Tag = subDir;
                aNode.ImageKey = "folder";
                subSubDirs = subDir.GetDirectories();
                if (subSubDirs.Length != 0)
                {
                    GetDirectories(subSubDirs, aNode);
                }
                nodeToAddTo.Nodes.Add(aNode);
            }
           }
           catch (Exception ex)
           {
               MessageBox.Show("2" + ex.Message);
           }
        }
        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {
            try
            {
            }
            catch (Exception ex)
            {
                MessageBox.Show("3" + ex.Message);
            }
        }
        void treeView1_NodeMouseClick(object sender,
            TreeNodeMouseClickEventArgs e)
        {
            try
            {
            TreeNode newSelected = e.Node;
            listView1.Items.Clear();
            DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
            ListViewItem.ListViewSubItem[] subItems;
            ListViewItem item = null;

            foreach (DirectoryInfo dir in nodeDirInfo.GetDirectories())
            {
                item = new ListViewItem(dir.Name, 0);
                subItems = new ListViewItem.ListViewSubItem[]
            {new ListViewItem.ListViewSubItem(item, "Directory"), 
             new ListViewItem.ListViewSubItem(item, 
                dir.LastAccessTime.ToShortDateString())};
                item.SubItems.AddRange(subItems);
                listView1.Items.Add(item);
            }
            foreach (FileInfo file in nodeDirInfo.GetFiles())
            {
                item = new ListViewItem(file.Name, 1);
                subItems = new ListViewItem.ListViewSubItem[]
            { new ListViewItem.ListViewSubItem(item, "File"), 
             new ListViewItem.ListViewSubItem(item, 
                file.LastAccessTime.ToShortDateString())};

                item.SubItems.AddRange(subItems);
                listView1.Items.Add(item);
            }

            listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            }
            catch (Exception ex)
            {
                MessageBox.Show("4" + ex.Message);
            }
        }

        private void btnGetFiles_Click(object sender, EventArgs e)
        {
           // PopulateTreeView
        }


    }
}

Open in new window

0
Comment
Question by:Mike Eghtebas
  • 2
  • 2
4 Comments
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 40517759
Are you sure the path exists? I changed your path, and it works fine for me:

Screenshot
0
 
LVL 33

Author Comment

by:Mike Eghtebas
ID: 40517832
As you can see, the folder path is correct. It drops "Public" for some reason. Apparently this is harmless because in steping through the code I can see it is able to read subfolder "UntypeDatasetSample".

Also, when I shortened the path to "C:\Users\Public", and because subfolder "My Music" is in "C:\Users\Public", it gives me access denied message despite the fact I have signed in as admin. Furthermore, right-click on "My Music"/Properties/ didn't give me security option to change its access permission settings.

Conclution: (it seems I have two problems)
1. Why doesn't it allow the code to aud certain folders despite the fact I have signed as admin (this item could be handled in another post).

2. Why it doesn't build tree-view for "C:\Users\Public\Documents\UntypeDatasetSample" where it doesn't need access requirements. I understand your test is valid and it works in your test. I will build another form to see if I have managed to mess it up while building my form.

FileAudit
0
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 500 total points
ID: 40517886
It's due to the behavior of Windows 7:

http://support.microsoft.com/kb/930128

You can't access these "folders"--that's by design. You go through the redirected location(s), which are under the user's profile folder.
0
 
LVL 33

Author Closing Comment

by:Mike Eghtebas
ID: 40517935
Thank you.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now