这篇文章介绍了如何得到本地系统信息,通过使用System.Management和Sysetm.IO 来得到文件夹和文件信息,并且把它们显示到TreeView、ListView控件z之中。
首先可以使用ManagementObjectSearcher类来查询system.management域,来获取返回ManagementOjbectCollection,在这个对象中,包含了我们所需要的信息,包括盘,文件夹,文件,现在让我们来看一下整个源码:
System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem menuItem4;
private System.Windows.Forms.TreeView tvFolders;
private System.Windows.Forms.ListView lvFiles;
private System.Windows.Forms.ImageList m_imageListTreeView;
private System.ComponentModel.IContainer components;
///
这里是ide自动产生的
///
private void PopulateDriveList()
{
TreeNode nodeTreeNode;
int imageIndex = 0;
int selectIndex = 0;
const int Removable = 2;
const int LocalDisk = 3;
const int Network = 4;
const int CD = 5;
this.Cursor = Cursors.WaitCursor;
tvFolders.Nodes.Clear();//清空树
nodeTreeNode = new TreeNode("My Computer",0,0);//
tvFolders.Nodes.Add(nodeTreeNode);
TreeNodeCollection nodeCollection = nodeTreeNode.Nodes;
ManagementObjectCollection queryCollection = getDrives();
foreach ( ManagementObject mo in queryCollection)
{
switch (int.Parse( mo["DriveType"].ToString()))
{
case Removable: //可移动盘
imageIndex = 5;
selectIndex = 5;
break;
case LocalDisk: //本地磁盘
imageIndex = 6;
selectIndex = 6;
break;
case CD: //光盘
imageIndex = 7;
selectIndex = 7;
break;
case Network: //网络驱动盘
imageIndex = 8;
selectIndex = 8;
break;
default: //默认
imageIndex = 2;
selectIndex = 3;
break;
}
//建立驱动盘的节点
nodeTreeNode = new TreeNode(mo["Name"].ToString() + "\\" ,imageIndex,selectIndex);
nodeCollection.Add(nodeTreeNode);
}
//Init files ListView
InitListView();
this.Cursor = Cursors.Default;
}
private void tvFolders_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
this.Cursor = Cursors.WaitCursor;
//获取当前选择的节点或则文件夹
TreeNode nodeCurrent = e.Node;
//清除掉所有的节点
nodeCurrent.Nodes.Clear();
if (nodeCurrent.SelectedImageIndex == 0)
{
PopulateDriveList();
}
else
{
PopulateDirectory(nodeCurrent, nodeCurrent.Nodes);
}
this.Cursor = Cursors.Default;
}
protected void InitListView()
{
//开始初始化 ListView 控件
lvFiles.Clear();
//为察看列表框建立头信息栏
lvFiles.Columns.Add("Name",150,System.Windows.Forms.HorizontalAlignment.Left);
lvFiles.Columns.Add("Size",75, System.Windows.Forms.HorizontalAlignment.Right);
lvFiles.Columns.Add("Created", 140, System.Windows.Forms.HorizontalAlignment.Left);
lvFiles.Columns.Add("Modified", 140, System.Windows.Forms.HorizontalAlignment.Left);
}
protected void PopulateDirectory(TreeNode nodeCurrent, TreeNodeCollection nodeCurrentCollection)
{
TreeNode nodeDir;
int imageIndex = 2;
int selectIndex = 3;
if (nodeCurrent.Selecte