Matthewj
Matthewj

Reputation: 2022

How to list all subdirectories in a directory

I'm working on a project and I need to list all subdirectories in a directory. For example, how could I list all the subdirectories in drive C:?

Upvotes: 108

Views: 271359

Answers (7)

R-D
R-D

Reputation: 634

To just get the simple list of folders without full path, you can use:

Directory.GetDirectories(parentDirectory).Select(d => Path.GetRelativePath(parentDirectory, d))

Upvotes: 3

mostafa-hajian
mostafa-hajian

Reputation: 53

Show all directories and subdirectories

def dir():

    from glob import glob

    dir = []

    dir = glob("path")

def all_sub_dir(dir):
    {
        for item in dir:
            {
                b = "{}\*".format(item)
                dir += glob(b)
            }
            print(dir)
    }

Upvotes: -3

Hakan SUMNULU
Hakan SUMNULU

Reputation: 93

Use:

FolderBrowserDialog fbd = new FolderBrowserDialog();

DialogResult result = fbd.ShowDialog();

string[] files = Directory.GetFiles(fbd.SelectedPath);
string[] dirs = Directory.GetDirectories(fbd.SelectedPath);

foreach (string item2 in dirs)
{
    FileInfo f = new FileInfo(item2);

    listBox1.Items.Add(f.Name);
}

foreach (string item in files)
{
    FileInfo f = new FileInfo(item);

    listBox1.Items.Add(f.Name);
}

Upvotes: 8

Mayur Narula
Mayur Narula

Reputation: 150

Use:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TRIAL
{
    public class Class1
    {
        static void Main(string[] args)
        {
           string[] fileArray = Directory.GetDirectories("YOUR PATH");
           for (int i = 0; i < fileArray.Length; i++)
           {
               Console.WriteLine(fileArray[i]);
           }
           Console.ReadLine();
        }
    }
}

Upvotes: 5

Clive
Clive

Reputation: 36956

It is as easy as this:

string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);

Upvotes: 74

Akash Shah
Akash Shah

Reputation: 171

Here's the best and fastest way to list all directories and subdirectories by skipping System.UnauthorizedAccessException:

A simple recursive method with an action to retrieve at realtime, preparing a list and returning to parent takes a lot of time. This callback function helps a lot to retrieve at realtime instead of preparing and returning back.

using System.IO;

private static void ListDirectories(string Path, Action<string> Listen){
    try
    {
        foreach(string Node in Directory.GetDirectories(Path)){
            Listen(Node);
            ListDirectories(Node, Listen);
        }
    } catch {}
}

Usage

static void Main(string[] args)
{
    ListDirectories(@"C:\", (dir) =>
    {
        Console.WriteLine(dir);
    });
}

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66449

Use Directory.GetDirectories to get the subdirectories of the directory specified by "your_directory_path". The result is an array of strings.

var directories = Directory.GetDirectories("your_directory_path");

By default, that only returns subdirectories one level deep. There are options to return all recursively and to filter the results, documented here, and shown in Clive's answer.


Avoiding an UnauthorizedAccessException

It's easily possible that you'll get an UnauthorizedAccessException if you hit a directory to which you don't have access.

You may have to create your own method that handles the exception, like this:

public class CustomSearcher
{ 
    public static List<string> GetDirectories(string path, string searchPattern = "*",
        SearchOption searchOption = SearchOption.AllDirectories)
    {
        if (searchOption == SearchOption.TopDirectoryOnly)
            return Directory.GetDirectories(path, searchPattern).ToList();

        var directories = new List<string>(GetDirectories(path, searchPattern));

        for (var i = 0; i < directories.Count; i++)
            directories.AddRange(GetDirectories(directories[i], searchPattern));

        return directories;
    }

    private static List<string> GetDirectories(string path, string searchPattern)
    {
        try
        {
            return Directory.GetDirectories(path, searchPattern).ToList();
        }
        catch (UnauthorizedAccessException)
        {
            return new List<string>();
        }
    }
}

And then call it like this:

var directories = CustomSearcher.GetDirectories("your_directory_path");

This traverses a directory and all its subdirectories recursively. If it hits a subdirectory that it cannot access, something that would've thrown an UnauthorizedAccessException, it catches the exception and just returns an empty list for that inaccessible directory. Then it continues on to the next subdirectory.

Upvotes: 189

Related Questions