添加treeView 和 listView 两个控件
{ public class MyFile { public float FileLength { get; set; }//文件大小(KB) public string FileName { get; set; }//文件名 public string FilePath { get; set; }//文件路径 public string FileType { get; set; }//文件类型 } }
主窗体的代码:
public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); } TreeNode tn; //定义一个节点 private void FrmMain_Load(object sender, EventArgs e) { //检索计算机上的所有逻辑驱动器的驱动器名称。 DriveInfo[] di = DriveInfo.GetDrives(); foreach (DriveInfo item in di) { tn = new TreeNode(item.Name); tn.Tag = item.Name; tv01.Nodes.Add(tn); } } //单击绑定文件和文件夹信息 private void tv01_AfterSelect(object sender, TreeViewEventArgs e) { TreeNode tn = tv01.SelectedNode; BingInfo(tn); } private void BingInfo(TreeNode tn) { //清空 listView1.Items.Clear(); //绑定子目录 DirectoryInfo dic = new DirectoryInfo(tn.Tag.ToString()); DirectoryInfo[] info = dic.GetDirectories(); foreach (DirectoryInfo item in info) { TreeNode temp = new TreeNode(); temp.Text = item.Name; temp.Tag = item.FullName; tn.Nodes.Add(temp); } //获取目录下文件列表 FileInfo[] fileinfo = dic.GetFiles(); //定义泛型集合存储文件信息 List<MyFile> files = new List<MyFile>(); //遍历文件列表 foreach (FileInfo it in fileinfo) { MyFile file = new MyFile(); file.FileName = it.Name; file.FileLength = it.Length; file.FileType = it.Extension; file.FilePath = it.FullName; files.Add(file); } //绑定到listview中 foreach (MyFile em in files) { ListViewItem lv = new ListViewItem(em.FileName); lv.SubItems.Add(em.FileLength.ToString()); lv.SubItems.Add(em.FileType); lv.SubItems.Add(em.FilePath); listView1.Items.Add(lv); } } private void 复制ToolStripMenuItem_Click(object sender, EventArgs e) { //判断是否选中 if (listView1 .SelectedItems .Count ==0) { return; } //提示用户选择目标文件夹 FolderBrowserDialog fbd = new FolderBrowserDialog(); DialogResult result = fbd.ShowDialog(); //源文件路径 string sourcepath = listView1.SelectedItems[0].SubItems[3].Text; //目标文件路径 string despath = null; //如果正确选择目标位置,执行复制操作 if (result==DialogResult .OK ) { despath = fbd.SelectedPath; //lvlist表示显示文件信息的ListView对象 despath += "\" + listView1.SelectedItems[0].SubItems[0].Text; //复制文件 File.Copy(sourcepath ,despath ); MessageBox.Show("复制成功!"); } } private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) { string delectpath = listView1.SelectedItems[0].SubItems[3].Text; File.Delete(delectpath); MessageBox.Show("删除成功!"); }