C# IO操作(五)文件的递归加载

      本篇是一个案例,其核心通过代码展示代码中的递归这个用法,程序的界面如下:

当点击“加载”按钮时,根据路径中的地址,加载该文件夹下所有的子文件夹和子文件,代码如下:

 1 private void BtnLoad_Click(object sender, EventArgs e)
 2         {
 3             string sPath = txtPath.Text.Trim();
 4             LoadDirAndFile(sPath, tvList.Nodes);
 5         }
 6 
 7         private void LoadDirAndFile(string sPath, TreeNodeCollection treeNodeCollection)
 8         {
 9             string strDir = sPath.Substring(sPath.LastIndexOf(@"\") + 1);
10             TreeNode tNode = treeNodeCollection.Add(strDir);
11 
12             //加载所有目录
13             string[] strDir1 = Directory.GetDirectories(sPath);
14             foreach (string item in strDir1)
15             {
16                 //返回目录的最后一级(名称)
17                 string sDir = item.Substring(item.LastIndexOf(@"\") + 1);
18                 TreeNode tNode1 = tNode.Nodes.Add(sDir);
19                 LoadDirAndFile(item, tNode1.Nodes);     //递归加载
20             }
21 
22             string[] strFiles = Directory.GetFiles(sPath, "*.txt");
23             foreach (string item in strFiles)
24             {
25                 TreeNode tNodeFile = treeNodeCollection.Add(Path.GetFileName(item));
26                 tNodeFile.Tag = item;
27             }
28         }
29 
30         private void tvList_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
31         {
32             if (e.Node.Tag!=null)
33             {
34                 //文件节点
35                 txtContent.Text = File.ReadAllText(e.Node.Tag.ToString(), Encoding.Default);
36             }
37         }

     总结:

     1.加载文件夹节点时,要考虑到文件夹下还有可能有子文件夹和子文件,所以要使用递归加载;

     2.在实现点击文件节点,要在右边的文本框中查看文本文件全部的内容,就在递归加载文件夹和文件时,为所有的文件节点加了tag属性,后面双击节点时,只要tag属性不为空即为文件节点(读取即可),而为空的则是文件夹节点(不需要处理)。

posted on 2014-08-02 01:07  chens2865  阅读(266)  评论(0编辑  收藏  举报

导航