views:

37

answers:

2

Hello.

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  A: 

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);
Kibbee
@Kibbee, It works well.
Nano HE
But he asked for the subfolder name, not the full path name. this answer gives you:C:\myapp\mainfolder\subfolder1C:\myapp\mainfolder\subfolder2C:\myapp\mainfolder\subfolder3
C Johnson
Quite, right, although the original poster marked it as accepted, so I guess it was good enough. If you want more meta data about the subdirectories, and not just their paths, you can use the DirectoryInfo (See MSDN) class.
Kibbee
Yes, I combined Kibbee's input and `DirectoryInfo` in my project.
Nano HE
+1  A: 

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.

C Johnson
@C Johnson, Thanks a lot for your input.
Nano HE