写了个简单的类,递归得到给定目录下的所有子目录,但是发觉只能得到第一层,不知道代码哪里逻辑有错误,请大家帮忙看看,头有点晕~谢谢!
    class utils
    {
        private List<string> folderAll = new List<string>();
        
        public List<string> FolderAll
        {
            get
            {
                return this.folderAll;
            }
        }        public void getAllFolders(string folderParent)
        {
            DirectoryInfo foldRoot = new DirectoryInfo(folderParent);
            
            if (foldRoot.Exists)
            {
                DirectoryInfo[] foldSubs = foldRoot.GetDirectories();                foreach (DirectoryInfo foldSub in foldSubs)
                {
                    this.folderAll.Add(foldSub.Name);
                    getAllFolders(foldSub.Name.ToString());
                }
            }
        }
    }

解决方案 »

  1.   

    foldSub.Name
    修改为
    foldSub.FullName
      

  2.   

    还有lz不停的new DirectoryInfo很好玩吗?
    改用DirectoryInfo来递归不是更方便?
      

  3.   

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;namespace ConsoleApplication2
    {
        class utils
        {
            private List<string> folderAll = new List<string>();        public List<string> FolderAll
            {
                get
                {
                    return this.folderAll;
                }
            }        public void getAllFolders(string folderParent)
            {
                DirectoryInfo foldRoot = new DirectoryInfo(folderParent);            if (foldRoot.Exists)
                {
                    DirectoryInfo[] foldSubs = foldRoot.GetDirectories();
                    
                    
                    
                    foreach (DirectoryInfo foldSub in foldSubs)
                    {
                        this.folderAll.Add(foldSub.FullName);
                        getAllFolders(foldSub.FullName.ToString());
                    }
                }
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                utils u = new utils();
                u.getAllFolders(@"e:\s");
                foreach (string s in u.FolderAll)
                {
                    Console.WriteLine(s.ToString());            }
                Console.ReadLine();
            }
        }
    }
    2楼正确啊,是路径问题啊,要使用全路径,而不是目录名字
      

  4.   

    2楼是我自己囧不停的new新对象当然不好,把这个对象移到函数外面,每次用的时候先empty一次,是这个意思?
      

  5.   

    public void getAllFolders(DirectoryInfo folderParent)
    这么定义方法不就可以了
    再加个string的重载,就能和原来一样的方式调用了