0

I want to list all the folders and their subfolders and theirs till reaching to deepest folder.

I have written a method like this:

public void scanFolders(string path)
{
    foreach (var dir in new DirectoryInfo(path).GetDirectories("*", SearchOption.AllDirectories))
    {
        listBox_Folders.Items.Add(dir.Name);
    }
}

This brings me all the folders and subfolders. It is OK

But I need a little different solution. I want to list subfolders of a folder just beneath its parent starting with a hyphen (-).

It should look like

<select>
    <option>folder1</option>
    <option>-subfolder11</option>
    <option>folder2</option>
    <option>-subfolder21</option>
    <option>-subfolder22</option>
</select>

What I have is

<select>
    <option>folder1</option>
    <option>folder2</option>
    <option>subfolder11</option>
    <option>subfolder21</option>
    <option>subfolder22</option>
</select>
1
  • Why can't you try to load on demand, sub folder data when user click on the folder. Commented Sep 22, 2014 at 19:24

2 Answers 2

1

You can use recursion

    private void ScanFolder(String prefix, String path)
    {
        foreach (var dir in new DirectoryInfo(path).GetDirectories("*", SearchOption.TopDirectoryOnly))
        {
            listBox_Folders.Items.Add(prefix + dir.Name);

            ScanFolder(prefix + "-", dir.FullName);
        }
    }

First call like ScanFolder(String.Empty, 'yourpathhere');

Sign up to request clarification or add additional context in comments.

Comments

1

Try adding a sort by FullName before iterating.

    foreach (var dir in new DirectoryInfo(path)
        .GetDirectories("*", SearchOption.AllDirectories)
        .OrderBy(d => d.FullName))
    {
        listBox_Folders.Items.Add(dir.Name);
    }

2 Comments

OrderBy is not accepted. I mean it is underlined with red line. Could it be a version issue? I use VS2010.
@Please check if you have System.Linq namespace included

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.