借助TreeView控件遍历本地磁盘并生成目录树时间:2022-12-24 12:39:34下面是实现的具体方法,逻辑很简单,就没有给说明了: ...... DriveInfo[] drivers = DriveInfo.GetDrives(); foreach (DriveInfo di in drivers) { SelectDirNFiles(this.treeView1.Nodes.Add(di.Name), di.Name); } ...... private void SelectDirNFiles(TreeNode tn,string path) { if (!Directory.Exists(path)) return; DirectoryInfo dirInfo = new DirectoryInfo(path); DirectoryInfo[] dirs = dirInfo.GetDirectories(); foreach (DirectoryInfo di in dirs) { TreeNode tnode = new TreeNode(di.Name); tnode.ForeColor = Color.Red; int currentIndex = tn.Nodes.Add(tnode); try { if (di.GetDirectories().Length > 0) { SelectDirNFiles(tn.Nodes[currentIndex], di.FullName); } } catch { //异常日志 } Application.DoEvents(); } foreach (FileInfo fi in dirInfo.GetFiles()) { tn.Nodes.Add(fi.Name); } Application.DoEvents(); }