0
点赞
收藏
分享

微信扫一扫

9、指定路径获取路径下目录结构

凯约 2022-03-12 阅读 25

 一、封装的函数

基本思想:主要是一个递归,判断object类型是文件还是文件夹,然后再放入发入对应的集合中

        /// <summary>
        /// 220305 komla 
        /// </summary>
        /// <param name="list"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        private static List<DirInfo> ListDirectory(List<DirInfo> list,string path)
        {
            DirectoryInfo folder = new DirectoryInfo(@path);
            //遍历文件
            foreach (FileInfo NextFile in folder.GetFiles())
            {
                //Console.WriteLine(path + NextFile.Name + "\r\n");
                //richTextBox1.AppendText(path + NextFile.Name + "\r\n");//文件路径
                list.Add(new DirInfo
                {
                    FileName = NextFile.Name,
                    //state = new state { opened = false }, 
                });
            }

            //遍历文件夹
            foreach (DirectoryInfo NextFolder in folder.GetDirectories())
            {

                list.Add(new DirInfo
                {
                    DirName = NextFolder.Name,
                    DirChildren = ListDirectory(new List<DirInfo>(), NextFolder.FullName)
                });
                //ListDirectory(new List<FileNames>(), NextFolder.FullName);

            }
            return list;
        }

二、类

    public class DirInfo
    {
        public DirInfo()
        {
            DirChildren = new List<DirInfo>();
        }

        public string DirName { get; set; }

        public string FileName { get; set; }

        public List<DirInfo> DirChildren { get; set; }
    }

说明:大家可以根据自己需求写这个类,比如文件类型了,文件大小了等

举报

相关推荐

0 条评论