Guilherme Longo
Guilherme Longo

Reputation: 57

Getting all sub directories using recursion

I am fetching a list of all directories and sub directories in my computer. I am using recursion.

Its ok until I perform the actuall recursion

I get this error:

System.NullReferenceException: Object reference not set to an instance of an object. 
at tgpwebged.Views.Admin.recursiveFileTree.WalkDirectoryTree(DirectoryInfo root) 
in s:\Projects\tgpwebged\tgpwebged\Views\Admin\recursiveFileTree.cs:line 93

this is the class:

static void WalkDirectoryTree(System.IO.DirectoryInfo root)
    {
        System.IO.DirectoryInfo[] subDirs = null;

        try
        {
            DirectoryInfo[] SubDirs = root.GetDirectories("*.*", SearchOption.TopDirectoryOnly);

            foreach(DirectoryInfo sdir in SubDirs) {
                log.Add(sdir.ToString());
            }

        }
        catch (Exception e)
        {
            log.Add("Exceção: " + e.ToString());
        }

        try
        {
            foreach (System.IO.DirectoryInfo dirInfo in subDirs)
            {
                log.Add(dirInfo.ToString());
                WalkDirectoryTree(dirInfo);
            }
        }
        catch (Exception e)
        {
            log.Add("Exceção: " + e.ToString());
            log.Add("");
        }
     }  

As you can see, the last for each gets the list of subdir in a dir and call the function again performing the recursion.

This class receive the all top directories from a Logical driver and go deep to the last directory structure.

Upvotes: 0

Views: 3322

Answers (3)

Jodrell
Jodrell

Reputation: 35726

C# is case sensitive,

SubDirs is not subdirs

You declare both, use both but only instantiate one.


Your sanitised function (not class) should be,

static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
    foreach(var subDirectory in root.GetDirectories(
        "*.*", 
        SearchOption.AllDirectories))
    {
        log.Add(subDirectory.ToString());
    }
}

However, it would make sense to pass log into the function.

Upvotes: 2

bhuang3
bhuang3

Reputation: 3633

You delcare System.IO.DirectoryInfo[] subDirs = null;

But you use DirectoryInfo[] SubDirs

Upvotes: 2

Dismissile
Dismissile

Reputation: 33071

It looks like you have two different variable that are named the same thing with different cases:

System.IO.DirectoryInfo[] subDirs = null;
DirectoryInfo[] SubDirs = root.GetDirectories("*.*", SearchOption.TopDirectoryOnly);

You are trying to iterate over subDirs but you never actually set it anywhere.

// subDirs is always null because you never set it to anything other than null
// in the variable declaration
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
    log.Add(dirInfo.ToString());
    WalkDirectoryTree(dirInfo);
}

Upvotes: 2

Related Questions