-2

Possible Duplicate:
How can I perform full recursive directory & file scan?

I can't find any informations, how to create a full directory listing in C#, including all files inside and all its subfolders's files, i.e:

c:\a.jpg
c:\b.php
c:\c\d.exe
c:\e\f.png
c:\g\h.mpg
Community
  • 1
  • 1
Tony
  • 12,405
  • 36
  • 126
  • 226

2 Answers2

6

You can use DirectoryInfo.GetFiles("C:\*.*", SearchOption.AllDirectories);

This will return an array of FileInfo objects, which include a Name and FullName property for the filename.

That being said, I would not do this on "C:\", as you'll return a huge array, but this technique will work correctly on an appropriate folder.

If you're using .NET 4, I'd recommend using EnumerateFiles instead, which will return an IEnumerable<T> instead of an array.

Note that the above code will most likely fail, however, as it requires full permissions to search the file system. A SecurityException will be raised if you can't access specific parts of the file system you're trying to search.

Also - if you're only interested in the file names and not the full FileInfo information, you can use Directory.EnumerateFiles instead, which returns an IEnumerable<string> with all of the relevant filenames.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

There is an MSDN Article with code examples to do just this.

This is the money:

void DirSearch(string sDir) 
{
    try 
    {
        foreach (string d in Directory.GetDirectories(sDir)) 
        {
            foreach (string f in Directory.GetFiles(d, txtFile.Text)) 
            {
                lstFilesFound.Items.Add(f);
            }
            DirSearch(d);
        }
    }
    catch (System.Exception excpt) 
    {
        Console.WriteLine(excpt.Message);
    }
}
Codeman
  • 12,157
  • 10
  • 53
  • 91