#region 依据目录填充树视图 /// <summary> /// 依据文件夹目录,填充树视图 /// </summary> /// <param name="dirPath">跟目录路径</param> /// <param name="loopflag">是否循环子文件夹</param> public void FillTreeView(TreeView treeView, string dirPath, bool loopflag) { try { // 检查目标目录是否以目录分割字符结束如果不是则添加之 if (dirPath[dirPath.Length - 1] != System.IO.Path.DirectorySeparatorChar) { dirPath += System.IO.Path.DirectorySeparatorChar; } // 判断目标目录是否存在如果不存在则新建之 if (!System.IO.Directory.Exists(dirPath)) { DialogResult result = MessageBox.Show(dirPath + " 目录不存在是否创建?", "提示", MessageBoxButtons.YesNo); if (DialogResult.Yes == result) { System.IO.Directory.CreateDirectory(dirPath); } else { return; } } treeView.Nodes.Clear(); //string tempPath = dirPath.Substring(0, dirPath.Length - 1); //string dir = tempPath.Substring(tempPath.LastIndexOf(System.IO.Path.DirectorySeparatorChar), tempPath.Length); TreeNode rootNode = new TreeNode(); rootNode.Text = dirPath; rootNode.Tag = dirPath; treeView.Nodes.Add(rootNode); string[] fileList = null; if (!loopflag) { // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法 fileList = Directory.GetFiles(dirPath); } else { // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组 fileList = System.IO.Directory.GetFileSystemEntries(dirPath); } AddNodes(rootNode, fileList, loopflag); } catch (Exception ex) { MessageBox.Show("目录树视图显示失败! " + ex); //throw; } } public void AddNodes(TreeNode parentNode, string[] fileList, bool loopflag) { try { // 遍历所有的文件和目录 foreach (string file in fileList) { TreeNode nowNode = new TreeNode(); string filename = file.Substring(file.LastIndexOf(System.IO.Path.DirectorySeparatorChar)); nowNode.Text = filename; //nowNode.Text = file; nowNode.Tag = file; parentNode.Nodes.Add(nowNode); if (System.IO.Directory.Exists(file)) { string[] fllist = System.IO.Directory.GetFileSystemEntries(file); AddNodes(nowNode, fllist, loopflag); } } } catch (System.Exception ex) { throw ex; } } #endregion