效果图如图所示:
一:读取目录下的子目录信息
通过TreeNode向TreeView中添加根节点,其次绑定子目录以及获取目录下的文件列表,在TreeView双击事件中进行调用
//单击绑定文件和文件夹信息 private void treeList_AfterSelect(object sender, TreeViewEventArgs e) { TreeNode node = this.treeList.SelectedNode; this.BindInfo(node); } public void ShowTree() { TreeNode tn = new TreeNode(); tn.Tag="C:\"; tn.Text = "C:\"; treeList.Nodes.Add(tn); TreeNode tn1 = new TreeNode(); tn1.Tag = "D:\"; tn1.Text = "D:\"; treeList.Nodes.Add(tn1); TreeNode tn2 = new TreeNode(); tn2.Tag = "E:\"; tn2.Text = "E:\"; treeList.Nodes.Add(tn2); } //将目录绑定到TreeView中 private void BindInfo(TreeNode node) { //绑定子目录 DirectoryInfo dir = new DirectoryInfo(node.Tag.ToString()); DirectoryInfo[] dirs = dir.GetDirectories(); foreach (DirectoryInfo di in dirs) { TreeNode temp = new TreeNode(); temp.Text = di.Name; temp.Tag = di.FullName; node.Nodes.Add(temp); } //获取目录下文件列表 FileInfo[] fileInfo = dir.GetFiles(); if (lvList!=null) { lvList.Items.Clear(); } //绑定 foreach (FileInfo item in fileInfo) { ListViewItem list = new ListViewItem(item.Name); list.SubItems.Add((item.Length/1024.0).ToString()); list.SubItems.Add(item.Extension); list.SubItems.Add(item.FullName); lvList.Items.Add(list); } }
二:实现文件复制
①:在右键菜单的响应事件中实现文件移动
②:通过“浏览文件夹”窗体使用FolderBrowserDialog类
③:文件复制使用File类的Copy()方法
关键代码如下:
//复制 private void tsmCopy_Click(object sender, EventArgs e) { if (this.lvList.SelectedItems.Count == 0) { return; } //提示用户选择目标文件夹 FolderBrowserDialog fdb = new FolderBrowserDialog(); DialogResult result = fdb.ShowDialog(); //源文件路径 string sourcePath = lvList.SelectedItems[0].SubItems[3].Text; //目标文件路径 string desPath = null; //如果正确选择目标位置,执行复制操作 if (result == DialogResult.OK) { desPath = fdb.SelectedPath; //lvList表示显示文件信息的ListView对象 desPath += "\" + lvList.SelectedItems[0].SubItems[0].Text; //复制文件 File.Copy(sourcePath,desPath); MessageBox.Show("复制成功!"); } }
三:实现文件删除
//删除 private void tsmDele_Click(object sender, EventArgs e) { if (this.lvList.SelectedItems.Count == 0) { return; } FileInfo fi = new FileInfo(lvList.SelectedItems[0].SubItems[3].Text); fi.Delete(); if (lvList != null) { TreeNode node = this.treeList.SelectedNode; this.BindInfo(node); } MessageBox.Show("删除成功!"); }
四:获取文件路径 打开文件
private void lvList_DoubleClick(object sender, EventArgs e) { string path = lvList.SelectedItems[0].SubItems[3].Text; Process.Start(path); }
Process代表进程、需引入命名空间:using System.Diagnostics;