你的位置:首页 > ASP.net教程

[ASP.net教程]基于Treeview控件遍历本地磁盘


一、前言

      Treeview控件常用于遍历本地文件信息,通常与Datagridview与ImageList搭配。ImageList控件用于提供小图片给TreeView控件,DatagridView通常显示TreeNode节点下文件及文件夹的信息。

效果图:

     

二、代码

初始化窗体:

private void ManagerForm_Load(object sender, EventArgs e)    {      InitialDataGridView(dgv_Local); //初始化本地dgv            InitialTreeView(); //初始化本地tree    }

 

初始化DataGridView:

 public void InitialDataGridView(DataGridView dgv)    {      DataGridViewColumn dgv_check = new DataGridViewCheckBoxColumn();      dgv_check.HeaderText = "选择";      dgv.Columns.Add(dgv_check);      DataGridViewColumn dgv_name = new DataGridViewTextBoxColumn();      dgv_name.HeaderText = "名称";      dgv.Columns.Add(dgv_name);      dgv_name.ReadOnly = true;      DataGridViewColumn dgv_length = new DataGridViewTextBoxColumn();      dgv_length.HeaderText = "大小";      dgv.Columns.Add(dgv_length);      dgv_length.ReadOnly = true;      DataGridViewColumn dgv_type = new DataGridViewTextBoxColumn();      dgv_type.HeaderText = "类型";      dgv.Columns.Add(dgv_type);      dgv_type.ReadOnly = true;      DataGridViewColumn dgv_version = new DataGridViewTextBoxColumn();      dgv_version.HeaderText = "版本";      dgv.Columns.Add(dgv_version);      dgv_version.ReadOnly = true;      dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;      dgv.AllowUserToAddRows = false;      dgv.RowHeadersVisible = false;      dgv.AllowUserToResizeRows = false;      dgv.Columns[0].Width = (int)((double)(dgv.Width) * 0.1);      dgv.Columns[1].Width = (int)((double)(dgv.Width) * 0.45);    }

 

初始化本地TreeView:

public void InitialTreeView()    {           TreeNode tv_mycomputer = new TreeNode("我的电脑");      tv_mycomputer.ImageIndex = 0;      tv_mycomputer.SelectedImageIndex = 0;      tv_Local.Nodes.Add(tv_mycomputer);      DriveInfo[] drives = DriveInfo.GetDrives();      string driveName = "";      foreach (DriveInfo drive in drives)      {        switch (drive.DriveType)        {          case DriveType.Fixed:            driveName = "本地磁盘(" + drive.Name.Substring(0, 2) + ")";            break;          case DriveType.Removable:            driveName = "可移动磁盘(" + drive.Name.Substring(0, 2) + ")";            break;          case DriveType.CDRom:            driveName = "DVD驱动器(" + drive.Name.Substring(0, 2) + ")";            break;          case DriveType.Network:            driveName = "网络驱动器(" + drive.Name.Substring(0, 2) + ")";            break;          default:            driveName = "未知(" + drive.Name + ")";            break;        }        TreeNode tr_cd = new TreeNode();        tr_cd.Text = driveName;        tr_cd.ImageIndex = 1;        tr_cd.SelectedImageIndex = 1;        LoadDirectory(Path.GetFullPath(drive.Name), tr_cd); //取得第一级磁盘信息        tv_mycomputer.Nodes.Add(tr_cd);      }    }

 

LoadDirectory方法:

public void LoadDirectory(string path, TreeNode tNode)    {      try      {        //遍历文件夹信息        string[] directorys = Directory.GetDirectories(path);         foreach (string item in directorys)        {          if ((File.GetAttributes(item) & FileAttributes.Hidden) != FileAttributes.Hidden)          {            TreeNode tn_Dir = new TreeNode(Path.GetFileName(item));            tn_Dir.ImageIndex = 2;            tn_Dir.SelectedImageIndex = 2;            tn_Dir.Name = item;            tNode.Nodes.Add(tn_Dir);          }        }        if (path.Contains("System Volume Information"))        {          return;        }        //遍历文件信息        string[] files = Directory.GetFiles(path);        foreach (string item in files)        {          string eName = Path.GetExtension(item);          if ((File.GetAttributes(item) & FileAttributes.Hidden) != FileAttributes.Hidden)          {            TreeNode tn_file = new TreeNode(Path.GetFileNameWithoutExtension(item));            tn_file.ImageIndex = 3;            tn_file.SelectedImageIndex = 3;            tn_file.Name = item;            tNode.Nodes.Add(tn_file);          }        }      }      catch { }    }    

 

AfterExpand方法:用于点击Node时快速加载,而不是在窗体加载时直接加载整个电脑的磁盘信息,因为那样太慢了

 private void tv_Local_AfterExpand(object sender, TreeViewEventArgs e)    {      if (e.Node.Level >= 1)      {        foreach (TreeNode tnode in e.Node.Nodes)        {          tnode.Nodes.Clear();          if (!Path.HasExtension(tnode.Name))          {            LoadDirectory(tnode.Name, tnode);          }        }      }    }

 

NodeMouseClick:点击Node显示该节点信息

private void tv_Local_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)    {      Thread.Sleep(100);      if(e.Node.FullPath=="我的电脑")      {        txt_Local.Text = "My Computer";      }      else if(e.Node.FullPath.Contains("(")&&e.Node.Level<=1)      {        txt_Local.Text = e.Node.FullPath.Split('\\')[1].Split('(')[1].Replace(')','\\');      }      else      {        txt_Local.Text = e.Node.Name;        this.dgv_Local.Rows.Clear();        if (e.Node.Level > 1)        {          Loadallinfo(e.Node.Name, dgv_Local);        }      }          }

 

Loadallinfo:用于DataGridview显示信息

 public void Loadallinfo(string path,DataGridView dgv)    {      if (Directory.Exists(path))      {        try        {          string[] directorys = Directory.GetDirectories(path); //获取选中treeview节点的子目录          foreach (string item in directorys)          {            if ((File.GetAttributes(item) & FileAttributes.Hidden) != FileAttributes.Hidden)            {              int index = dgv.Rows.Add();              dgv.Rows[index].Cells[1].Value = item;              dgv.Rows[index].Cells[2].Value = CountSize(GetDirectoryLength(item)).ToString();              dgv.Rows[index].Cells[3].Value = "文件夹";              dgv.Rows[index].Cells[4].Value = "";            }          }          if (path.Contains("System Volume Information"))          {            return;          }          string[] files = Directory.GetFiles(path);          foreach (string item in files)          {            string eName = Path.GetExtension(item);            if ((File.GetAttributes(item) & FileAttributes.Hidden) != FileAttributes.Hidden)            {              int index = dgv.Rows.Add();              dgv.Rows[index].Cells[1].Value = item;              System.IO.FileInfo file = new System.IO.FileInfo(item);              dgv.Rows[index].Cells[2].Value = CountSize(file.Length).ToString();              dgv.Rows[index].Cells[3].Value = Path.GetExtension(item);              if (Path.GetExtension(item) == ".dll")              {                FileVersionInfo ver = FileVersionInfo.GetVersionInfo(item);                dgv.Rows[index].Cells[4].Value = ver.FileVersion;              }              else              {                dgv.Rows[index].Cells[4].Value = "";              }            }          }        }        catch { }      }      else if (File.Exists(path))      {        try        {          string item = path;          int index = dgv.Rows.Add();          dgv.Rows[index].Cells[1].Value = item;          dgv.Rows[index].Cells[2].Value = CountSize(item.Length).ToString();          dgv.Rows[index].Cells[3].Value = Path.GetExtension(item);          if (Path.GetExtension(item) == ".dll")          {            FileVersionInfo ver = FileVersionInfo.GetVersionInfo(item);            dgv.Rows[index].Cells[4].Value = ver.FileVersion;          }          else          {            dgv.Rows[index].Cells[4].Value = "";          }        }        catch { }      }    }

 

计算文件大小:

 #region 文件大小换算    public static string CountSize(long Size)    {      string m_strSize = "";      long FactSize = 0;      FactSize = Size;      if (FactSize < 1024.00)        m_strSize = FactSize.ToString("F2") + " B";      else if (FactSize >= 1024.00 && FactSize < 1048576)        m_strSize = (FactSize / 1024.00).ToString("F2") + " K";      else if (FactSize >= 1048576 && FactSize < 1073741824)        m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " M";      else if (FactSize >= 1073741824)        m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " G";      return m_strSize;    }    #endregion    #region 文件夹大小计算    public static long GetDirectoryLength(string path)    {      if (!Directory.Exists(path))      {        return 0;      }      long size = 0;      DirectoryInfo di = new DirectoryInfo(path);      foreach (FileInfo fi in di.GetFiles())      {        size += fi.Length;      }      DirectoryInfo[] dis = di.GetDirectories();      if (dis.Length > 0)      {        for (int i = 0; i < dis.Length; i++)        {          size += GetDirectoryLength(dis[i].FullName);        }      }      return size;    }    #endregion