Manipulations on directories.

Hi,

I want to write a generic program to get the directory and all the sub directpries under it.

The code which I have with me works only till next immediate sub directory

Like

string strDirName = @"E:\Cirrus";

DirectoryInfo di = new DirectoryInfo(strDirName);

if (di.Exists)

{

DirectoryInfo[] subDir = di.GetDirectories();

foreach (DirectoryInfo dirInfo in subDir)

{

Console.WriteLine(dirInfo.FullName);

DirectoryInfo [] nestDir = dirInfo.GetDirectories();

foreach ( DirectoryInfo info in nestDir )

{

Console.WriteLine(info.FullName);

}

}

Console.ReadLine();

}

So this will display next 2 levels of directories

But let say I have Test/Test1/Test2/Test3..../Testn then how can achieve this goal

I want to make this program generic.

Regards,




Answer this question

Manipulations on directories.

  • Ltl Hawk

    Here you go:

    string[] dir = Directory.GetDirectories(@"E:\Cirrus\", "*.*", SearchOption.AllDirectories);

    foreach (string d in dir)

    {

    Console.WriteLine(d);

    }



  • DiasVFX

    You need to do the recursion from/to the same function as Galin has suggested, Try his code, I hope you'll get it done.

    Best Regards,

    Rizwan aka RizwanSharp



  • ihendry01

    as you do not know how deep you're going this is good example for recursion

    void DumpDirectories(string path)
            {
                DirectoryInfo di = new DirectoryInfo(path);
                if (di.Exists)
                {
                    DirectoryInfo[] nestDir = di.GetDirectories();
                    foreach (DirectoryInfo info in nestDir)
                    {
                        Console.WriteLine(info.FullName);
                        //go deeper
                        DumpDirectories(info.FullName);
                    }
                }
            }

    Hope this helps



  • Manipulations on directories.