using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace lesson9_34
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
private void FrmMain_Load(object sender, EventArgs e)
{
loadRootNode();
}
//添加磁盘
private void loadRootNode()
{
TreeNode node = new TreeNode();
node.Text = "D:\\";
node.Tag = "D:\\";
this.tvFile.Nodes.Add(node);
}
private void BindInfo(TreeNode node)
{
//绑定子目录
DirectoryInfo DI = new DirectoryInfo(node.Tag.ToString());
DirectoryInfo[] dirs = DI.GetDirectories();
foreach (DirectoryInfo di in dirs)
{
TreeNode temp = new TreeNode();
temp.Text = di.Name;
temp.Tag = di.FullName;
node.Nodes.Add(temp);
}
//绑定目录的文件
FileInfo[] fileInfo = DI.GetFiles();
List<MyFile> files = new List<MyFile>();
foreach (FileInfo myfile in fileInfo)
{
MyFile file = new MyFile();
file.FileName = myfile.Name;
file.FileLength = myfile.Length;
file.FilePath = myfile.FullName;
file.FileType = myfile.Extension;
files.Add(file);
}
//绑定Listview
ListViewItem item = null;
this.lvFile.Items.Clear();
foreach (MyFile file in files)
{
item = new ListViewItem();
item.Text = file.FileName;
item.SubItems.Add(file.FileLength.ToString());
item.SubItems.Add(file.FileType);
item.SubItems.Add(file.FilePath);
this.lvFile.Items.Add(item);
}
}
private void tvFile_AfterSelect(object sender, TreeViewEventArgs e)
{
TreeNode node = this.tvFile.SelectedNode;
this.BindInfo(node);
}
//Copy复制
private void tsmiCopy_Click(object sender, EventArgs e)
{
if (this.lvFile.SelectedItems.Count == 0)
{
return;
}
FolderBrowserDialog fb = new FolderBrowserDialog();
DialogResult result = fb.ShowDialog();
//提示用户选择文件
string sourcePath = lvFile.SelectedItems[0].SubItems[3].Text;
//源文件路径
string desPath = null;
//正确选择,执行复制操作
if (result == DialogResult.OK)
{
try
{
desPath = fb.SelectedPath;
desPath += "/" + lvFile.SelectedItems[0].SubItems[0].Text;
//复制文件
File.Copy(sourcePath, desPath);
MessageBox.Show("复制成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//删除文件
private void tsmiDelete_Click(object sender, EventArgs e)
{
if (this.lvFile.SelectedItems.Count == 0)
{
return;
}
//删除的文件
string sourcePath = lvFile.SelectedItems[0].SubItems[3].Text;
DialogResult result = MessageBox.Show("确定要删除?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if (result == DialogResult.OK)
{
File.Delete(sourcePath);
MessageBox.Show("删除成功!");
}
//刷新一下
this.lvFile.SelectedItems[0].Remove();
}
}
}