在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → TreeView目录文件浏览简单代码

TreeView目录文件浏览简单代码

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.25M
  • 下载次数:72
  • 浏览次数:835
  • 发布时间:2019-02-01
  • 实例类别:C#语言基础
  • 发 布 人:无聊啊~~
  • 文件格式:.rar
  • 所需积分:2
 相关标签: ee 文件 tree 目录 浏览

实例介绍

使用双缓冲TreeView,listView,实现目录文件浏览,代码简单400行,不闪烁,可显示文件夹不同状态图标,可应用于自定义的文件对话框等,可根据需要自行继续简化。

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Disk1
{
    public partial class Form1 : Form
    {
        public static class getIcon
        {
            [DllImport("Shell32.dll")]
            static extern int SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, int cbFileInfo, uint uFlags);

            struct SHFILEINFO
            {
                public IntPtr hIcon;
                public int iIcon;
                public int dwAttributes;
                public char szDisplayName;
                public char szTypeName;
            }

            static public Icon GetFileIcon(string fileName, bool smallIcon)
            {
                SHFILEINFO fi = new SHFILEINFO();
                Icon ic = null;
                int iTotal = (int)SHGetFileInfo(fileName, 100, ref fi, 0, (uint)(smallIcon ? 273 : 272));
                if (iTotal > 0)
                {
                    ic = Icon.FromHandle(fi.hIcon);
                }
                return ic;
            }
        }

        public class TreeViewEx : TreeView
        {
            protected override void OnHandleCreated(EventArgs e)
            {
                SendMessage(this.Handle, TVM_SETEXTENDEDSTYLE, (IntPtr)TVS_EX_DOUBLEBUFFER, (IntPtr)TVS_EX_DOUBLEBUFFER);
                base.OnHandleCreated(e);
            }
            private const int TVM_SETEXTENDEDSTYLE = 0x1100   44;
            private const int TVM_GETEXTENDEDSTYLE = 0x1100   45;
            private const int TVS_EX_DOUBLEBUFFER = 0x0004;
            [DllImport("user32.dll")]
            private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
        }

        public class ListViewEx : ListView
        {
            public ListViewEx()
            {
                SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
                UpdateStyles();
            }
        }

        TreeViewEx treeView1;
        ListViewEx listView1;

        public static int BrowNumber = 0, BrowRecord = 0, AssNumber = 0;

        public class RecordBrow
        {
            public string Dir_Name;
            public RecordBrow(string _name)
            {
                Dir_Name = _name;
                BrowNumber  = 1;
            }
        }
        public static List<RecordBrow> recordBrows = new List<RecordBrow>();

        public class FileAssociated
        {
            public int Id;
            public string AssociatedType;
            public Bitmap AssociatedIcon;
            public FileAssociated(int _id, string _type, Bitmap _icon)
            {
                Id = _id;
                AssociatedType = _type;
                AssociatedIcon = _icon;
            }
        }
        public static List<FileAssociated> fileAssociateds = new List<FileAssociated>();

        public class DirectoryFile
        {
            public string Fullname;
            public string DFname;
            public string DFtype;
            public int DFicon;
            public string DFtime;
            public long DFsize;
            public int DFflag;
            public DirectoryFile(string _full, string _name, string _type,int _icon, string _time,long _size,int _flag)
            {
                Fullname = _full;
                DFname = _name;
                DFtype = _type;
                DFicon = _icon;
                DFtime = _time;
                DFsize = _size;
                DFflag = _flag;
            }
        }
        public static List<DirectoryFile> directoryFiles = new List<DirectoryFile>();

        public Form1()
        {
            InitializeComponent();
            treeView1 = new TreeViewEx()
            {
                ItemHeight = 22,
                Size = new Size(376, 546),
                Location = new Point(12, 41),
                Font = new Font("微软雅黑", 9),
                ImageList = imageList1,
                ShowLines = false,
                ShowRootLines = false,
                ShowPlusMinus = false,
            };
            treeView1.NodeMouseClick  = treeView1_NodeMouseClick;
            this.Controls.Add(treeView1);

            listView1 = new ListViewEx()
            {
                Size = new Size(515, 547),
                Location = new Point(442, 40),
                Font = new Font("微软雅黑", 9),
                View = View.Details,
                GridLines = false,
                SmallImageList = imageList2,
                FullRowSelect = true,
            };
            listView1.Columns.Add("文件名", 120, HorizontalAlignment.Left);
            listView1.Columns.Add("文件类型", 120, HorizontalAlignment.Left);
            listView1.Columns.Add("修改时间", 120, HorizontalAlignment.Left);
            listView1.Columns.Add("大小", 120, HorizontalAlignment.Left);
            listView1.DoubleClick  = ListView1_DoubleClick;
            this.Controls.Add(listView1);

            ManagementObjectCollection queryCollection = getDrives();
            treeView1.Nodes.Clear();
            foreach (ManagementObject mo in queryCollection)
            {
                TreeNode node1 = new TreeNode();
                node1.Text = mo["Name"].ToString();
                node1.Name = mo["Name"].ToString()   "\\";
                node1.ImageIndex = 0;
                node1.Tag = 0;
                treeView1.Nodes.Add(node1);
            }
            get_SubDirFile(treeView1.Nodes[0].Name);
            SearchNode(treeView1.Nodes, treeView1.Nodes[0].Name);

            recordBrows.Add(new RecordBrow(treeView1.Nodes[0].Name));
        }

        protected ManagementObjectCollection getDrives()
        {
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk ");
            ManagementObjectCollection queryCollection = query.Get();
            return queryCollection;
        }

        public void get_SubDirFile(string _path)
        {
            directoryFiles.Clear();
            listView1.Items.Clear();
            DirectoryInfo dir = new DirectoryInfo(_path);
            try
            {
                DirectoryInfo[] subDirector = dir.GetDirectories();
                for (int i = 0; i < subDirector.Length; i  )
                {
                    directoryFiles.Add(new DirectoryFile(subDirector[i].FullName, subDirector[i].FullName.Replace(_path, "").Replace("\\", "") ,"文件夹",0 , 
                        subDirector[i].LastWriteTime.ToShortDateString()   subDirector[i].LastWriteTime.ToShortTimeString(),0,0));
                }
            } catch { }

            DirectoryInfo Files = new DirectoryInfo(_path);
            try
            {
                FileInfo[] files = Files.GetFiles("*.*");
                for (int i = 0; i < files.Length; i  )
                {
                    string _type = GetFileTypeDesection(files[i].Extension);
                    int img_Index = 0;
                    var _fa = fileAssociateds.Where(fa=>fa.AssociatedType==_type).ToList();
                    if (_fa.Count<1)
                    {
                        Bitmap _bmp = new Bitmap(20, 20);
                        Graphics g = Graphics.FromImage(_bmp);
                        g.DrawImage(getIcon.GetFileIcon(files[i].FullName, true).ToBitmap(),new PointF(2,2));
                        imageList2.Images.Add(_bmp);
                        AssNumber  = 1;
                        img_Index = AssNumber;
                    }  else
                    {
                        img_Index = _fa[0].Id   1;
                    }
                    directoryFiles.Add(new DirectoryFile(files[i].FullName, files[i].FullName.Replace(_path, "").Replace("\\", ""), _type, img_Index, 
                        files[i].LastWriteTime.ToShortDateString()  files[i].LastWriteTime.ToShortTimeString(), files[i].Length,1));
                }
            } catch { }
            listView1.BeginUpdate();
            for (int i=0;i<directoryFiles.Count;i  )
            {
                ListViewItem lvi = new ListViewItem();
                lvi.ImageIndex = directoryFiles[i].DFicon;
                lvi.Text = directoryFiles[i].DFname;
                lvi.SubItems.Add(directoryFiles[i].DFtype);
                lvi.SubItems.Add(directoryFiles[i].DFtime);
                if (directoryFiles[i].DFflag==0) lvi.SubItems.Add("");
                else lvi.SubItems.Add(directoryFiles[i].DFsize.ToString("N0"));
                listView1.Items.Add(lvi);
            }
            listView1.EndUpdate();
        }

        public void get_SubDir()
        {
            if (treeView1.SelectedNode.Nodes.Count < 1)
            {
                DirectoryInfo dir = new DirectoryInfo(treeView1.SelectedNode.Name);
                try
                {
                    DirectoryInfo[] subDirector = dir.GetDirectories();
                    for (int i = 0; i < subDirector.Length; i  )
                    {
                        TreeNode node1 = new TreeNode();
                        node1.Name = subDirector[i].FullName;
                        node1.Tag = 1;
                        node1.ImageIndex = 2;
                        node1.SelectedImageIndex = 2;
                        DirectoryInfo has_sub = new DirectoryInfo(node1.Name);
                        try
                        {
                            DirectoryInfo[] hasDir = has_sub.GetDirectories();
                            if (hasDir.Length < 1)
                            {
                                node1.ImageIndex = 4;
                                node1.SelectedImageIndex = 4;
                                node1.Tag = 4;
                            }
                        }
                        catch
                        {
                            node1.ImageIndex = 4;
                            node1.SelectedImageIndex = 4;
                            node1.Tag = 4;
                        }
                        node1.Text = node1.Name.Replace(treeView1.SelectedNode.Name, "").Replace("\\", "");
                        treeView1.SelectedNode.Nodes.Add(node1);
                    }
                }
                catch { }
            }
        }

        private void SearchNode(TreeNodeCollection tnds, string text)
        {
            foreach (TreeNode tnd in tnds)
            {
                if (tnd.Name.Equals(text))   
                {
                    treeView1.SelectedNode = tnd;
                    break;
                }
                if (tnd.Nodes.Count != 0)
                {
                    SearchNode(tnd.Nodes, text);
                }
            }
            textBox1.Text = text;
            treeView1.Focus();
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            get_SubDirFile(e.Node.Name);
            SearchNode(treeView1.Nodes, e.Node.Name);
            get_SubDir();
            if (e.Node.Nodes.Count < 1)
            {
                if ((int)e.Node.Tag == 0)
                {
                    e.Node.SelectedImageIndex = 0;
                    e.Node.ImageIndex = 0;
                }
                else
                if ((int)e.Node.Tag == 1)
                {
                    e.Node.SelectedImageIndex = 4;
                    e.Node.ImageIndex = 4;
                }
            }
            else
            {
                if (e.Node.IsExpanded)
                {
                    e.Node.Collapse();
                    if ((int)e.Node.Tag == 0)
                    {
                        e.Node.SelectedImageIndex = 0;
                        e.Node.ImageIndex = 0;
                    }
                    else
                    if ((int)e.Node.Tag == 1)
                    {
                        e.Node.SelectedImageIndex = 2;
                        e.Node.ImageIndex = 2;
                    }
                    setchild(e.Node);
                }
                else
                {
                    e.Node.Expand();
                    if ((int)e.Node.Tag == 0)
                    {
                        e.Node.SelectedImageIndex = 1;
                        e.Node.ImageIndex = 1;
                    }
                    else
                    if ((int)e.Node.Tag == 1)
                    {
                        e.Node.SelectedImageIndex = 3;
                        e.Node.ImageIndex = 3;
                    }
                }
            }
            Cursor = Cursors.Default;
            if (e.Node.Name!=recordBrows[BrowNumber-1].Dir_Name) // 最后浏览记录不相同就记录
            {
                BrowRecord  = 1;
                recordBrows.Add( new RecordBrow(e.Node.Name) );
            }
        }

        private void ListView1_DoubleClick(object sender, EventArgs e)
        {
            var items = listView1.SelectedItems;
            Cursor = Cursors.WaitCursor;
            int _index = listView1.Items[listView1.SelectedIndices[0]].Index;
            if (directoryFiles[_index].DFflag == 0)
            {
                if (directoryFiles[_index].Fullname != recordBrows[BrowNumber - 1].Dir_Name)
                {
                    BrowRecord  = 1;
                    recordBrows.Add(new RecordBrow(directoryFiles[_index].Fullname));
                }

                textBox1.Text = directoryFiles[_index].Fullname;
                SearchNode(treeView1.Nodes, directoryFiles[_index].Fullname);
                get_SubDirFile(directoryFiles[_index].Fullname);
                get_SubDir();
            }
            Cursor = Cursors.Default;
        }

        private void setchild(TreeNode node)
        {
            foreach (TreeNode child in node.Nodes)
            {
                if ((int)child.Tag == 0)
                {
                    child.ImageIndex = 0;
                } else
                if ((int)child.Tag == 1)
                {
                    child.ImageIndex = 2;
                }
                setchild(child);
            }
        }

        // 前进
        private void button1_Click(object sender, EventArgs e)
        {
            int _reco = (BrowRecord   1) > (BrowNumber - 1) ? (BrowNumber - 1) : (BrowRecord   1);
            if (_reco != BrowRecord)
            {
                BrowRecord = _reco;
                SearchNode(treeView1.Nodes, recordBrows[BrowRecord].Dir_Name);
                get_SubDirFile(recordBrows[BrowRecord].Dir_Name);
            }
            treeView1.Focus();
        }

        // 后退
        private void button2_Click(object sender, EventArgs e)
        {
            int _reco = (BrowRecord - 1) < 0 ? 0 : (BrowRecord - 1);
            if (_reco != BrowRecord)
            {
                BrowRecord = _reco;
                SearchNode(treeView1.Nodes, recordBrows[BrowRecord].Dir_Name);
                get_SubDirFile(recordBrows[BrowRecord].Dir_Name);
            }
            treeView1.Focus();
        }

        public static string GetFileTypeDesection(string _ext)
        {
            string value;
            try
            {
                string desc = (string)Registry.ClassesRoot.OpenSubKey(_ext).GetValue(null);
                if (desc != null) value = (string)Registry.ClassesRoot.OpenSubKey(desc).GetValue(null);
                else value = _ext.Replace(".", "")   " 文件";
            } catch
            {
                value = _ext.Replace(".","")   " 文件";
            }
            return value;
        }
    }
}


标签: ee 文件 tree 目录 浏览

实例下载地址

TreeView目录文件浏览简单代码

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警