user1814358
user1814358

Reputation: 619

Get directories and files with recursion?

Is possible to get all directories, subdirectories and files with recursion.

I do this because i want to increase my programming logic, and learn how recursion work.

I know to do that with this way:

 string path = "D://";
            string rezdir,newpath;
            DirectoryInfo di = new DirectoryInfo(path);
            DirectoryInfo[] dir = di.GetDirectories().ToArray();
            for (int i = 0; i < di.GetDirectories().Length; i++)
            {
                Console.WriteLine(dir[i].ToString());
            }
            Console.WriteLine("\n\nChoose File: ");
            rezdir = Console.ReadLine();
            newpath = path + rezdir;
            di = new DirectoryInfo(newpath);
            dir = di.GetDirectories().ToArray();
            for (int i = 0; i < di.GetDirectories().Length; i++)
            {
                Console.WriteLine(dir[i].ToString());
            }
            Console.ReadKey();

But i don't do that with recursion way, so ff someone can to do this, i'll be grateful to him.

Upvotes: 2

Views: 339

Answers (3)

Jay
Jay

Reputation: 10128

Going by the code you posted - you seem to want some user interaction - so try something like this:

 public static class RecursiveTest
{
    public static string Foo(DirectoryInfo currentPath)
    {
        if (!currentPath.Exists) return string.Empty;

        foreach (var directory in currentPath.EnumerateDirectories())
            Console.WriteLine("Directory {0}", directory.Name);

        foreach (var file in currentPath.EnumerateFiles())
            Console.WriteLine("File {0}", file.Name);

        while(true)
        {
            Console.WriteLine("Choose directory or file: ");
            string chosenPath = Console.ReadLine();

            string newPath = Path.Combine(currentPath.FullName, chosenPath);
            if(Directory.Exists(newPath))
                return Foo(new DirectoryInfo(newPath));

            if(File.Exists(newPath))
                return newPath;

            Console.WriteLine("File {0} doesn't exist!", newPath);
        }
    }
}

And call with something like this:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(RecursiveTest.Foo(new DirectoryInfo(@"d:\dev")));

        Console.ReadLine();
    }
}

HTH

Upvotes: 1

Saeed Neamati
Saeed Neamati

Reputation: 35852

Yeah, it's possible. But I do recommend that you first take a grasp of what recursion is. To put it simply, a recursion has a one-time executing part, and many-time executing part. That one time triggers the many-time part.

In this question, the one-time execution part might be to get the list of all directories beneath the root directory.

Then for each directory, you get all the sub-directories and files. This is the many-times part. However, to run a batch of codes many times, you need to bundle them into a callable routine, or procedure, or method, or function, whatever you call it. Just code bundle.

public void DoDirectories()
{
    // one-time part; get a list of directories to start with.
    List<string> rootDirectories = Directory.GetDirectories("c:\\").ToList();
    foreach (string rootDirectory in rootDirectories)
    {
        GetSubdirectories(rootDirectory);
    }
}

public List<string> GetSubdirectories(string parentDirectory)
{
    List<string> subdirecotries = Directory.GetDirectories(
        parentDirectory, "*.*", SearchOption.TopDirectoryOnly).ToList();
    foreach (string subdirectory in subdirecotries)
    {
        GetSubdirectories(subdirectory); // recursing happens here
    }
    return subdirecotries;
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

I will avoid coding, because this is a valuable learning exercise. Try completing it yourself: once you do, you'll know that you understand recursion.

To be recursive, a method needs to call itself. Imagine that a method

public static void ShowDirectory(int indentationLevel, DirectoryInfo path)

is already written for you. This makes it easier to write the body:

  1. Get all files in the directory, and print their names in the loop
  2. Get all directories in the directory, and show their content at the next indentation level. You need another loop for that.

The first step is a simple exercise in writing loops. The second exercise becomes easy, too, because you can think of the ShowDirectory as pre-written.

Upvotes: 1

Related Questions