我写的一个打开目录的代码,就是运行太慢了,请高手指教一下
解决方案名为:MyFileBrowser
下面是代码的内容:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace MyFileBrowser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] drives = Directory.GetLogicalDrives();
int count = drives.Length;
TreeNode[] tn = new TreeNode[count];
DirectoryInfo di;
string driveName;
for (int i = 0; i < count; i++)
{
try
{
di = new DirectoryInfo(drives[i]);
driveName = di.Name;
tn[i] = new TreeNode(driveName, getNodes(drives[i]));
}
catch (Exception)
{
di = new DirectoryInfo(drives[i]);
driveName = di.Name;
tn[i] = new TreeNode(driveName);
}
}
TreeNode tr = new TreeNode("我的电脑", tn);
treeView1.Nodes.Add(tr);
//treeView1.ExpandAll();
}
private TreeNode[] getNodes(string path)
{
string[] paths = Directory.GetDirectories(path);
int count = paths.Length;
TreeNode[] tn = new TreeNode[count];
DirectoryInfo di;
string pathName;
if (count != 0)
{
for (int i = 0; i < count; i++)
{
try
{
di = new DirectoryInfo(paths[i]);
pathName = di.Name;
tn[i] = new TreeNode(pathName, getNodes(paths[i]));
}
catch (Exception)
{
di = new DirectoryInfo(paths[i]);
pathName = di.Name;
tn[i] = new TreeNode(pathName);
}
}
}
return tn;
}
private void button1_Click(object sender, EventArgs e)
{
string str = treeView1.SelectedNode.FullPath;
str = str.Replace("我的电脑\\", "");
str = str.Replace("\\\\", "\\");
MessageBox.Show(str, "选择的目录");
treeView1.Select();
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}