效果如图:
实现代码:
using System;
using System.IO;
using System.Windows.Forms;
using System.Configuration;
namespace 磁盘管理
{
public partial class frmMain : Form
{
private bool isfirst = true;
private string path = ConfigurationManager.AppSettings["Path"].ToString();
public frmMain()
{
InitializeComponent();
PopulateTreeView();
}
private void PopulateTreeView()
{
TreeNode rootNode;
DirectoryInfo info = new DirectoryInfo(path);
if (info.Exists)
{
rootNode = new TreeNode(info.Name);
rootNode.Tag = info;
GetDirectories(info.GetDirectories(), rootNode);
treeView1.Nodes.Add(rootNode);
}
}
private void GetDirectories(DirectoryInfo[] subDirs, TreeNode nodeToAddTo)
{
TreeNode aNode;
DirectoryInfo[] subSubDirs;
foreach (DirectoryInfo subDir in subDirs)
{
aNode = new TreeNode(subDir.Name, 0, 0);
aNode.Tag = subDir;
aNode.ImageKey = "folder";
subSubDirs = subDir.GetDirectories();
if (subSubDirs.Length != 0)
{
GetDirectories(subSubDirs, aNode);
}
nodeToAddTo.Nodes.Add(aNode);
}
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode newSelected = e.Node;
listView1.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;
foreach (DirectoryInfo dir in nodeDirInfo.GetDirectories())
{
item = new ListViewItem(dir.Name, 0);
subItems = new ListViewItem.ListViewSubItem[]
{new ListViewItem.ListViewSubItem(item, "文件夹"),
new ListViewItem.ListViewSubItem(item,
dir.LastAccessTime.ToString("yyyy-MM-dd hh:mm:ss"))};
item.SubItems.AddRange(subItems);
listView1.Items.Add(item);
}
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
item = new ListViewItem(file.Name, 1);
string[] a = file.Name.Split('.');
subItems = new ListViewItem.ListViewSubItem[]
{ new ListViewItem.ListViewSubItem(item, FileType(a[a.Length-1])+" 文件"),
new ListViewItem.ListViewSubItem(item,
file.LastAccessTime.ToString("yyyy-MM-dd hh:mm:ss")),
new ListViewItem.ListViewSubItem(item,GetString(file.Length))};
item.SubItems.AddRange(subItems);
listView1.Items.Add(item);
}
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}
private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
if (isfirst)
{
e.Cancel = true;
isfirst = false;
}
}
private string FileType(string type)
{
if (type == "dll")
return "应用程序扩展";
if (type == "exe")
return "应用程序";
return type;
}
//文件大小处理
public string GetString(long b)
{
const int GB = 1024 * 1024 * 1024;
const int MB = 1024 * 1024;
const int KB = 1024;
if (b / GB >= 1)
{
return Math.Round(b / (float)GB, 2) + "GB";
}
if (b / MB >= 1)
{
return Math.Round(b / (float)MB, 2) + "MB";
}
if (b / KB >= 1)
{
return Math.Round(b / (float)KB, 2) + "KB";
}
return b + "B";
}
}
}
文件的增删改,移动等功能自己研究吧,,,哈哈都是简单的文件控制功能
参考链接:treeview和listview使用
源码地址:https://pan.baidu.com/s/1gA8-nak43Zt4F9K0zmoQTg 提取码: v29k