// <summary>
// 获取所有逻辑盘并列出硬盘所有目录
// </summary>
private void ListDrives()
{
TreeNode tn;
// 获取系统中的所有逻辑盘
string[] drives = Directory.GetLogicalDrives();
// 向树视图中添加节点
tvDir.BeginUpdate();
for(int i=0;i<drives.Length;i++)
{
// 根据驱动器的不同类型来确定所进行的操作
switch( GetDriveType( drives[i] ))
{
case 2: // 软驱
// 如果是软驱,则仅向树视图中添加节点
// 而不列举它的目录,并且它的图像索引以及
// 处于选择状态下的图像索引分别为0和0
tn = new TreeNode( drives[i] ,0,0);
break;
case 3: // 硬盘
// 如果是硬盘,则除了向树视图中添加节点外,
// 还要列举出它的目录
tn = new TreeNode( drives[i],1,1);
ListDirs(tn,drives[i]); // 列举硬盘中的目录
break;
case 5: // 光驱
// 如果是光驱,则仅向树视图中添加节点
tn = new TreeNode( drives[i],2,2);
break;
default: // 在默认情况下,按软驱的情况进行处理
tn = new TreeNode( drives[i] ,0,0);
break;
}
tvDir.Nodes.Add( tn ); // 把创建的节点添加到树视图中
}
tvDir.EndUpdate();
// 把C盘设为当前选择节点
tvDir.SelectedNode = tvDir.Nodes[1];
}
public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
nDirLevel = 0; // 把列举深度初始化为0
ListDrives(); // 获取逻辑驱动器并列出硬盘中的目录
}
// <summary>
// 递归列出指定目录的所有子目录
// </summary>
private void ListDirs(TreeNode tn,string strDir)
{
if( nDirLevel>4 ) // 调整该行语句,可以改变列举目录的深度
{
nDirLevel = 0;
return;
}
nDirLevel++;
string[] arrDirs;
TreeNode tmpNode;
try
{
// 获取指定目录下的所有子目录
arrDirs = Directory.GetDirectories( strDir);
if( arrDirs.Length == 0 ) return;
// 把每一个子目录添加到参数传递进来的树视图节点中
for( int i=0;i<arrDirs.Length;i++)
{
tmpNode = new TreeNode( Path.GetFileName(arrDirs
[i]),3,4 );
// 对于每一个子目录,都进行递归列举
ListDirs( tmpNode,arrDirs[i] );
tn.Nodes.Add( tmpNode );
}
}
catch
{
return;
}
}
// <summary>
// 列出指定目录下的所有子目录和文件
// </summary>
private void ListDirsAndFiles(string strDir)
{
ListViewItem lvi;
int nImgIndex;
string[] items = new String[4];
string[] dirs;
string[] files;
try
{
// 获取指定目录下的所有子目录
dirs = Directory.GetDirectories( strDir );
// 获取指定目录下的所有文件
files = Directory.GetFiles( strDir );
}
catch
{
return;
}
评论