Search code examples
c#.netdirectoryinfo

How do i list all directories and subdirectories in an unordered list


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();
        }

i would like the end result to be :

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

if anyone can help me please


Solution

  • 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>");
        }
    }
    

    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);