How can I detect all the sub folders under a giving main folder?

322 Views Asked by At

Assume my path is "c:/myapp/mainfolder/" there are three folder included in the main folder. BTW, It doesn't need to identify separate files under mainfolder.

c:/myapp/mainfolder/subfolder1/
c:/myapp/mainfolder/subfolder2/
c:/myapp/mainfolder/subfolder3/

How can I input c:/myapp/mainfoder/ and get the output: string[] subArrFolders = {subfolder1, subfolder2, subfolder3}

C#2.0 using.

Thank you.

2

There are 2 best solutions below

3
On BEST ANSWER

You can use Directory.GetDireatories() to get the sub directories of a known path. You can use it like this:

string MyPath = "c:\\myapp\\mainfolder\\";
string[] subArrFolders = IO.Directory.GetDiretories(MyPath);
1
On

For lack of better information this answer assumes he asked for the sub-folder name, not the full path name, which is what that will give you:

This will allow you extract the leaf folder name:

using System;
using System.Text;
using System.IO;

namespace StackOverflow_NET
{
    class Program
    {
        static void Main(string[] args)
        {
            String path = @"C:\myapp\mainfolder";
            DirectoryInfo info = new DirectoryInfo(path);
            DirectoryInfo [] sub_directories = info.GetDirectories("*",SearchOption.AllDirectories);

            foreach (DirectoryInfo dir in sub_directories)
            {
                Console.WriteLine(dir.Name);
            }
        }
    }
}

Output:

subfolder1
subfolder2
subfolder3

The key difference here is the DirectoryInfo class allows you to get the leaf directory name via the Name property.