如何在无序列表中列出所有目录和子目录 [英] How do i list all directories and subdirectories in an unordered list

查看:98
本文介绍了如何在无序列表中列出所有目录和子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我似乎无法克服的问题.我试图列出所有目录和子目录.这就是我到目前为止的代码:

I have this problem that i cant seem to overcome. i am trying to list all the directories and sub directories. This is what i have so far in code :

String[] Folders;
            String[] Files;
            path = Server.MapPath("/");

            DirectoryInfo dir = new DirectoryInfo(path);
            Folders = Directory.GetDirectories(path);

            try
            {
                FolderListing.Append("<ul id=\"FolderList\">");

                for (int x = 0; x < Folders.Length; x++ )
                {
                    DirectoryInfo folder = new DirectoryInfo(Folders[x]);

                    FolderListing.Append("<li>").Append(folder.Name).Append("</li>");
                    CheckSubdirectories(Folders[x]);
                }



                FolderListing.Append("</ul>");
                FolderList.Text = FolderListing.ToString();
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        private void CheckSubdirectories(string currentpath)
        {
           String[] subfolders = Directory.GetDirectories(currentpath);
           if (subfolders.Length != 0)
           {
               FolderListing.Append("<ul id=\"SubFolderList\">");
           }
            for (int x = 0; x < subfolders.Length; x++ )
            {
               DirectoryInfo sfolder = new DirectoryInfo(subfolders[x]);
               FolderListing.Append("<li>").Append(sfolder.Name).Append("</li>");
            }
            if (subfolders.Length != 0)
            {
                FolderListing.Append("</ul>");
            }
            path = currentpath.ToString();
        }

我希望最终结果是:

<ul>
    <li>admin</li>
    <ul>
        <li>Containers</li>
        <li>ControlPanel</li>
        <li>Menus</li>
        <ul>
            <li>etc etc</li>
        </ul>
    </ul>
</ul>

如果有人可以帮助我

推荐答案

希望此递归方法有助于:

Hope this recursive method helps:

void ListDirectories(string path, StringBuilder sb)
{
    var directories = Directory.GetDirectories(path);
    if (directories.Any())
    {
        sb.AppendLine("<ul>");
        foreach (var directory in directories)
        {
            var di = new DirectoryInfo(directory);
            sb.AppendFormat("<li>{0}</li>", di.Name);
            sb.AppendLine();
            ListDirectories(directory, sb);
        }
        sb.AppendLine("</ul>");
    }
}

要调用它,只需创建一个StringBuilder的实例,并将其与方法的路径一起发送:

To invoke it, just create an instance of StringBuilder and send it along with the path to the method:

var sb = new StringBuilder();
ListDirectories(Server.MapPath("/"), sb);

这篇关于如何在无序列表中列出所有目录和子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆