13

Possible Duplicate:
How to recursively list all the files in a directory in C#?

I want to list the "sub-path" of files and folders for the giving folder (path)

let's say I have the folder C:\files\folder1\subfolder1\file.txt

if I give the function c:\files\folder1\

I will get subfolder1 subfolder1\file.txt

Community
  • 1
  • 1
Data-Base
  • 8,418
  • 36
  • 74
  • 98
  • 4
    You've examined the API available with FileInfo and DirectoryInfo? Implementing the behavior you want is quite trivial with those classes... – Kirk Woll Sep 14 '10 at 15:59

5 Answers5

28

You can use the Directory.GetFiles method to list all files in a folder:

string[] files = Directory.GetFiles(@"c:\files\folder1\", 
    "*.*",
    SearchOption.AllDirectories);

foreach (var file in files)
{
    Console.WriteLine(file);
}

Note that the SearchOption parameter can be used to control whether the search is recursive (SearchOption.AllDirectories) or not (SearchOption.TopDirectoryOnly).

Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
26

Try something like this:

static void Main(string[] args)
{
    DirSearch(@"c:\temp");
    Console.ReadKey();
}

static void DirSearch(string dir)
{
    try
    {
        foreach (string f in Directory.GetFiles(dir))
            Console.WriteLine(f);
        foreach (string d in Directory.GetDirectories(dir))
        {
            Console.WriteLine(d);
            DirSearch(d);
        }

    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
5
String[] subDirectories;
String[] subFiles;
subDirectories = System.IO.Directory.GetDirectories("your path here");
subFiles = System.IO.Directory.GetFiles("your path here");
tonythewest
  • 456
  • 3
  • 13
  • Really easy and it rocks. But to get only names - foreach (String str in subDirectories) Console.WriteLine(str.Split('\\').Last()); foreach (String str in subFiles) Console.WriteLine(str.Split('\\').Last()); – sapatelbaps Nov 26 '13 at 17:51
0

Use the System.IO.Directory class and its methods

NullUserException
  • 83,810
  • 28
  • 209
  • 234
0

I remember solving a similar problem not too long ago on SO, albeit it was in VB. Here's the question.

Community
  • 1
  • 1
Alex Essilfie
  • 12,339
  • 9
  • 70
  • 108