C#_LoadFiles_recursive

//load the sub files and Directories

//get the path Name

---------------------------------------------------------------------------

pirvate void Form1_Load(object sender,EventArgs e)

{

  string exePath=Assembly.GetCurrentAssembly().Location;

  string exeDirectoryPath=Path.GetDirectoryName(exePath);

  string path=Path.Combine(exeDirectoryPath,"资料");

  LoadAllFilesAndDirectories(path,treeview1.Nodes);

}

-------------------------------------------------------------------------

//call the function  recursively

private void LoadAllFilesAndDirectories(string path ,TreeNodeCollection treeNodeCollection)

{

  //1.get all Directories Names under  the path

  string[]  allDirectoriesNames=Directory.GetDirectories(path);

  //2.add the directories mumber

  for(int i=0;i<allDirectoriesNames.Length;i++)

  {

    TreeNode  tn=treeNodeCollection.Add(Path.GetFileName(allDirectoriesNames[i]));

    LoadAllFilesAndDirectories(allDirectoriesNames[i],tn.Nodes);  //此处调用递归,传递的参数 为每个要显示的路径,以及每个节点的子节点集合

  }  

  

  //3.get all files Names under the path

  string[]  allFilesNames=Directory.GetFiles(path,"*.txt");

  for(int i=0;i<allFilesNames.Length;i++)

  {

    treeNodeCollection.Add(allFilesNames[i]);    //此处文件类型 可以用TreeNode 标签保存当前文件路径 以便取用

    //  TreeNode node=treeNodeCollection.Add(allFilesNames[i]);

           //  node.Tag=allFilesNames[i];                      //Tag 为Object类型

  }

}

---------------------------------------------------------------------

 //资料管理 添加TreeView的node双击事件  加载文件

private treeView1_NodeMouseDoubleClick(object sender,TreeNodeMouseClickEventArgs e)

{

  //可从传递的参数e中  获取当前选中节点信息  并加以判断   以上只有文件tag存储路径,文件夹则没有

  if(e.Node.Tag!=null)        //文件tag不为空

  {

    //获取以上保存的文件当前路径

    string currentPath=e.Node.Tag.ToString();

    string txt=File.ReadAllText(currentPath,Encoding.Default);

    TextBox1.Text=txt;

  }

  

}

原文地址:https://www.cnblogs.com/siyi/p/4826839.html