0

I'd like to browse a directory and get all files with their sizes , names and urls. I did like this :

 int i = 0;
                 foreach (string sFileName in Directory.GetFiles(Path.Combine(@"C:\Projets", path2)))
                 {
                     i++;
                 }

i count the number of files in a directory but the problem when i have other directories inside it , how can i do to get all files and it caracteristics?

Lamloumi2
  • 235
  • 1
  • 4
  • 12
  • 1
    possible duplicate of http://stackoverflow.com/questions/929276/how-to-recursively-list-all-the-files-in-a-directory-in-c – aquaraga May 30 '13 at 12:25
  • Put all this in a method Do a recursive call until you get no files at the end – Taj May 30 '13 at 12:28

2 Answers2

1

This is a duplicate of many other similar questions. If you want to get extended file info, use the XxxInfo classes, eg DirectoryInfo, FileInfo instead of the Directory and File classes.

Additionally, all GetXXX or EnumerateXXX methods have overloads with the SearchOption parameter which allows you to return all files,not just the files of the top directory.

For your specific question, to get info on all files below a directory using e.g. GetFiles:

var di=new DirectoryInfo(somePath);
var allFiles=di.GetFiles("*",SearchOption.AllDirectories);
foreach(var file in allFiles)
{
    Console.WriteLine("{0} {1}",file.Name,file.Length);
}

The difference between GetFiles and EnumerateFiles is that GetFiles returns only after it retrieves all files below a directory, which can take a long time. EnumerateFiles returns an iterator so you can use it in a foreach statement to process each file at a time and stop the iteration if you like by breaking out of the loop.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
0

This should loop through all of the files recursively

foreach (string sFileName in Directory.EnumerateFiles(Path.Combine(@"C:\Projets", path2), "*.*", SearchOption.AllDirectories))
        {
            //Get file information here
            FileInfo f = new FileInfo(sFileName);
            Console.WriteLine("{0} - {1}", f.Length, f.Name);
        }
rh072005
  • 720
  • 6
  • 15