資料管理器,Treeview,遞歸

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace _30_資料管理器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)

        {

            //將demo文件夾放在bin/debug下面,則可以直接調用,否則寫地址

            DirectoryInfo drecinfo = new DirectoryInfo("demo");


            DirectoryInfo[] infos = drecinfo.GetDirectories();


            foreach (var item in infos)

            {

                //將一級文件夾名添加到樹的一級節點

                TreeNode tnode = treeView1.Nodes.Add(item.Name);

                //循環遍歷每一個文件夾下的內容

                LoadData(item.FullName, tnode);
            }
        }


        private void LoadData(string path, TreeNode tnode)
        {
            //獲取當前節點下的直接文件
            string[] files = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly);
            foreach (var item in files )
            {
                //獲取當前路徑下的文件名:Path.GetFileName (item)


                //不包括擴展名

                tnode.Nodes.Add(Path.GetFileNameWithoutExtension(item));

                 

              //增加文件結點後,將該文件的路徑綁定到tag

              filenode.Tag= item;

                //包括擴展名
                //tnode.Nodes.Add(Path.GetFileName (item));
            }
            //獲取當前節點下的直接文件夾
            string[] direcs = Directory.GetDirectories(path);
            foreach (var item in direcs)
            {
                TreeNode node = tnode.Nodes.Add(Path.GetFileName (item));
                LoadData(item, node);
            }
        

        }

private voidtreeView1_AfterSelect(object sender, TreeViewEventArgs e)

        {

            if (e.Node != null)

            {

                if (e.Node.Tag != null)

                {

                     //讀取txt文件的內容——地址,編碼

                    textBox1 .Text =File.ReadAllText (e.Node .Tag.ToString (),Encoding.Default  );

                }

            }

        }


    }

}






發佈了84 篇原創文章 · 獲贊 18 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章