浏览我的电脑
2012-04-07 17:29 精诚所至 金石为开 阅读(355) 评论(0) 编辑 收藏 举报利用TreeView控件和ImageList控件显示我的电脑的结构目录:我的电脑-驱动器-文件夹,程序运行结果如下图所示。
程序代码如下。
using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace eg30_useTreeView { public partial class FolderDialog : Form { public FolderDialog() { InitializeComponent(); } private void ForderTree_AfterSelect(object sender, TreeViewEventArgs e) { if (e.Node.Text.ToString() != "我的电脑") EnumDirectories(e.Node); else EnumDrives(e.Node); } private void EnumDrives(TreeNode ParentNode) { if (ParentNode.Nodes.Count == 0) { foreach (string drive in Directory.GetLogicalDrives()) { FolderTree.SelectedNode = ParentNode; TreeNode TempNode = new TreeNode(); TempNode.Text = drive.Substring(0, drive.Length - 1); TempNode.Tag = drive; TempNode.ImageIndex = 1; TempNode.SelectedImageIndex = 1; FolderTree.SelectedNode.Nodes.Add(TempNode); FolderTree.SelectedNode.Nodes[FolderTree.SelectedNode.Nodes.Count - 1].EnsureVisible(); } } } private void EnumDirectories(TreeNode ParentNode) { FolderTree.SelectedNode = ParentNode; string DirectoryPath = ParentNode.Tag.ToString(); if (ParentNode.Nodes.Count == 0) { if (DirectoryPath.Substring(DirectoryPath.Length - 1) != @"\") DirectoryPath += @"\"; try { foreach (string directory in Directory.GetDirectories(DirectoryPath)) { TreeNode TempNode = new TreeNode(); TempNode.Text = directory.Substring(directory.LastIndexOf(@"\") + 1); TempNode.Tag = directory; TempNode.ImageIndex = 3; TempNode.SelectedImageIndex = 2; FolderTree.SelectedNode.Nodes.Add(TempNode); FolderTree.SelectedNode.Nodes[FolderTree.SelectedNode.Nodes.Count - 1].EnsureVisible(); } } catch (Exception) { } } } } }