C#:依据目录填充树视图
2014-04-22 19:22
429 查看
#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
相关文章推荐
- C# BackgroundWorker 多参数事件
- C#全角和半角转换
- C# 用正则表达式替换字符串中所有特殊字符
- 用C#将输入的小写字母转化为大写字母
- c#获取程序版本号
- 在C#中实现串口通信的方法
- (转)C# Enum,Int,String的互相转换 枚举转换
- C#:将空间数据加载到树视图控件
- C# Trace
- C# ListView用法详解
- ahjesus C# 4.0 Parallel 并行运算
- C# treeview默认选中一个节点
- C#IO操作,删除指定目录下的所有文件夹和文件
- C#数据导出到Excel中
- C# 基础备忘录
- C# 进程Process基本的操作说明
- c# -- 读取文件夹中的所有文件(备忘)
- 从零开始编写自己的C#框架(3)——开发规范(转)
- C# TextBox数字的输入
- C#高效导出Excel(IList转DataTable,DataSet)