List all files and directories in a directory + subdirectories

281,094

Solution 1

string[] allfiles = Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories);

where *.* is pattern to match files

If the Directory is also needed you can go like this:

 foreach (var file in allfiles){
     FileInfo info = new FileInfo(file);
 // Do something with the Folder or just add them to a list via nameoflist.add();
 }

Solution 2

Directory.GetFileSystemEntries exists in .NET 4.0+ and returns both files and directories. Call it like so:

string[] entries = Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories);

Note that it won't cope with attempts to list the contents of subdirectories that you don't have access to (UnauthorizedAccessException), but it may be sufficient for your needs.

Solution 3

public static void DirectorySearch(string dir)
{
    try
    {
        foreach (string f in Directory.GetFiles(dir))
        {
            Console.WriteLine(Path.GetFileName(f));
        }
        foreach (string d in Directory.GetDirectories(dir))
        {
            Console.WriteLine(Path.GetFileName(d));
            DirectorySearch(d);
        }
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Note: the function shows only names without relative paths.

Solution 4

Use the GetDirectories and GetFiles methods to get the folders and files.

Use the SearchOption AllDirectories to get the folders and files in the subfolders also.

Solution 5

I am afraid, the GetFiles method returns list of files but not the directories. The list in the question prompts me that the result should include the folders as well. If you want more customized list, you may try calling GetFiles and GetDirectories recursively. Try this:

List<string> AllFiles = new List<string>();
void ParsePath(string path)
{
    string[] SubDirs = Directory.GetDirectories(path);
    AllFiles.AddRange(SubDirs);
    AllFiles.AddRange(Directory.GetFiles(path));
    foreach (string subdir in SubDirs)
        ParsePath(subdir);
}

Tip: You can use FileInfo and DirectoryInfo classes if you need to check any specific attribute.

Share:
281,094
derp_in_mouth
Author by

derp_in_mouth

Updated on December 17, 2021

Comments

  • derp_in_mouth
    derp_in_mouth over 2 years

    I want to list every file and directory contained in a directory and subdirectories of that directory. If I chose C:\ as the directory, the program would get every name of every file and folder on the hard drive that it had access to.

    A list might look like

    fd\1.txt
    fd\2.txt
    fd\a\
    fd\b\
    fd\a\1.txt
    fd\a\2.txt
    fd\a\a\
    fd\a\b\
    fd\b\1.txt
    fd\b\2.txt
    fd\b\a
    fd\b\b
    fd\a\a\1.txt
    fd\a\a\a\
    fd\a\b\1.txt
    fd\a\b\a
    fd\b\a\1.txt
    fd\b\a\a\
    fd\b\b\1.txt
    fd\b\b\a
    
  • Lucero
    Lucero over 11 years
    Use Substring to cut off the left part of the name. :)
  • Lucero
    Lucero over 11 years
    Won't really work... Lsit<>class? What does GetFiles return? And what about the directory names which were also requested?
  • Guffa
    Guffa over 11 years
    The GetFiles method returns a string array.
  • Ruslan F.
    Ruslan F. over 11 years
    actualy...you are right... I'm learning Qt abaout 2 days ago and was mistaken a little
  • derp_in_mouth
    derp_in_mouth over 11 years
    This might work, but it often fails with an UnauthorizedAccessException. How would search only directories it can access?
  • Ruslan F.
    Ruslan F. over 11 years
    it means that in your system this app hasn't got enough permissions
  • default locale
    default locale about 9 years
    Your answer doesn't add anything new to an already existing top-voted answer.
  • Alastair Maw
    Alastair Maw almost 9 years
    It's also wrong, as this doesn't return any directories (as the question specified), only actual files.
  • Alex
    Alex almost 8 years
    It would improve your answer if you can add a little explanation of what the code does.
  • kayleeFrye_onDeck
    kayleeFrye_onDeck about 7 years
    It's probably file attributes, @derp_in_mouth ; even if I run a .NET app as Invoker, and I'm admin, if I say, want to delete a file that is R/O, I need to remove the Read-Only attribute before I can mess with it.
  • Steve Smith
    Steve Smith about 7 years
    This is by far the best answer here. It gets all files and folders in one line of code, which none of the others do.
  • PreguntonCojoneroCabrón
    PreguntonCojoneroCabrón about 7 years
    Using Tasks for big huge number files and directories ?
  • Markus
    Markus about 7 years
    msdn.microsoft.com/en-us/library/ff477033(v=vs.110).aspx is the Parallel Threading version of the above solution using a stack collection and quicker.
  • Gusdor
    Gusdor almost 7 years
    @Lucero How and why would you do that? Path offers more reliable methods.
  • Lucero
    Lucero almost 7 years
    @Gusdor Feel free to suggest a more suitable way using the Path for removing a fixed left part of the path, e.g. `C:` in the example given.
  • Gusdor
    Gusdor almost 7 years
    @Lucero my comment was poorly phrased. 'Use substring' doesnt tell me a lot and I had to get stuck into linqpad to derive a nice solution. For example, what would the parameter be? Are you going to do path.SubString(2) to naively remove drive letter and colon? What if the directory is a network share? I suggest Path as a reliable method because it can provide loads of goodies in this area. In this case, you may write filePath.Substring(Path.GetPathRoot(filePath).Length). Yes this uses Substring as it is the most concise.
  • MarthyM
    MarthyM almost 7 years
    Could you please provide an explanation or in-line comments, what your code does?
  • Sascha
    Sascha almost 7 years
    of course, done it, but it should be self explanatory, it's a simple looping recursion through all the directories and files
  • I.Step
    I.Step about 4 years
    It goes recursively through the directory and prints filenames or directory names. For every inner directory it calls the same function. For more information: stackoverflow.com/questions/929276/…
  • TidyDev
    TidyDev almost 4 years
    This does not get sub directories.
  • sairfan
    sairfan about 3 years
    To list all sub directories (not files) only based on file type string[] allDir = System.IO.Directory.GetDirectories(@"D:\\Images\", "*.jpg", SearchOption.AllDirectories);
  • Yen Dang
    Yen Dang over 2 years
    I get some hidden folders such as: "F:\$RECYCLE.BIN", "F:\System Volume Information". How to ignore these folder (get only files and folders display on view)
  • Caius Jard
    Caius Jard over 2 years
    @YenDang call File.GetAttributes on the path - the MSDN example code specifically demos hidden files