我正在尝试制作一个小型应用程序,并且需要显示所有文件夹才能选择特定的文件/文件夹。
我找到了一个较旧主题的源代码,但是它不起作用。我只能在某些地方看不到文件夹。
能请您看看并告诉我您的意见吗?
private void Form1_Load(object sender, EventArgs e)
{
string[] drives = Environment.GetLogicalDrives();
foreach (string drive in drives)
{
DriveInfo di = new DriveInfo(drive);
int driveImage;
switch (di.DriveType) //set the drive's icon
{
case DriveType.CDRom:
driveImage = 3;
break;
case DriveType.Network:
driveImage = 6;
break;
case DriveType.NoRootDirectory:
driveImage = 8;
break;
case DriveType.Unknown:
driveImage = 8;
break;
default:
driveImage = 2;
break;
}
TreeNode node = new TreeNode(drive.Substring(0, 1), driveImage, driveImage);
node.Tag = drive;
if (di.IsReady == true)
node.Nodes.Add("...");
dirsTreeView.Nodes.Add(node);
}
}
private void dirsTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (e.Node.Nodes.Count > 0)
{
if (e.Node.Nodes[0].Text == "..." && e.Node.Nodes[0].Tag == null)
{
e.Node.Nodes.Clear();
//get the list of sub direcotires
string[] dirs = Directory.GetDirectories(e.Node.Tag.ToString());
//add files of rootdirectory
DirectoryInfo rootDir = new DirectoryInfo(e.Node.Tag.ToString());
foreach (var file in rootDir.GetFiles())
{
TreeNode n = new TreeNode(file.Name, 13, 13);
e.Node.Nodes.Add(n);
}
foreach (string dir in dirs)
{
DirectoryInfo di = new DirectoryInfo(dir);
TreeNode node = new TreeNode(di.Name, 0, 1);
try
{
//keep the directory's full path in the tag for use later
node.Tag = dir;
//if the directory has sub directories add the place holder
if (di.GetDirectories().Count() > 0)
node.Nodes.Add(null, "...", 0, 0);
foreach (var file in di.GetFiles())
{
TreeNode n = new TreeNode(file.Name, 13, 13);
node.Nodes.Add(n);
}
}
catch (UnauthorizedAccessException)
{
//display a locked folder icon
node.ImageIndex = 12;
node.SelectedImageIndex = 12;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "DirectoryLister",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
e.Node.Nodes.Add(node);
}
}
}
}
}
谢谢您的支持!祝你有美好的一天!