界面做好了,那么怎样才能在这个界面里显示文件夹和文件呢?这需要我们添加代码来实现。
首先引用以下名字空间:
using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;using System.IO ;using System .Runtime .InteropServices ;在mainForm_Load事件中添加以下代码,用于在treeView控件中显示目录树:private void mainForm_Load(object sender, System.EventArgs e)//获取逻辑驱动器string[] LogicDrives=System.IO .Directory .GetLogicalDrives();TreeNode[] cRoot =new TreeNode[LogicDrives.Length];for (int i=0;i LogicDrives.Length ;i++){TreeNode drivesNode=new TreeNode(LogicDrives[i]);treeView.Nodes .Add (drivesNode);if (LogicDrives[i]!="A:\" && LogicDrives[i]!="B:\" )getSubNode(drivesNode,true);}}
其中,getSubNode为一方法,用于获取子目录,以创建目录树节点,参数:PathName为获取的子目录在此节点下创建子节点,参数isEnd:结束标志,true则结束。
private void getSubNode(TreeNode PathName,bool isEnd){if(!isEnd)return; //exit thisTreeNode curNode;DirectoryInfo[] subDir;DirectoryInfo curDir=new DirectoryInfo (PathName.FullPath);try{subDir=curDir.GetDirectories();}catch{}foreach(DirectoryInfo d in subDir){curNode=new TreeNode(d.Name);PathName.Nodes .Add (curNode);getSubNode(curNode,false);}}
当鼠标单击目录节点左边的+号时,节点将展开,此时,应在AfterExpand事件中加入以下代码,以获取此目录下的子目录节点:
private void treeView_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e){try{foreach(TreeNode tn in e.Node .Nodes ){if (!tn.IsExpanded)getSubNode(tn,true);}}catch{;}}
当鼠标单击选中目录节点时,右边的listView控件应显示此目录下的文件和目录,代码如下:
private void treeView_AfterSelect(object sender,System.Windows.Forms.TreeViewEventArgs e){listView.Items.Clear();DirectoryInfo selDir=new DirectoryInfo(e.Node.FullPath );DirectoryInfo[] listDir;FileInfo[] listFile;try{listDir=selDir.GetDirectories();listFile=selDir.GetFiles();}catch{}foreach (DirectoryInfo d in listDir)listView.Items .Add (d.Name,6);foreach (FileInfo d in listFile)listView.Items .Add (d.Name);}
至此,一个简单的文件浏览器就做成了,当然,它还很初级,甚至不能用它打开一个文件,加另外,它也不能显示文件和目录的图标,没有进行错误处理,没有进行安全控制它能给你的只是一个思路。