6

I need to determine the number of files/subdirectories in a directory. I don't care which files/directories are actually in that directory. Is there a more efficient way than using

_directoryInfo.GetDirectories().Length +
_directoryInfo.GetFiles().Length

Thanks.

Mav3rick
  • 776
  • 1
  • 7
  • 22
  • Duplicate: http://stackoverflow.com/questions/1192951/quicker-quickest-way-to-get-number-of-files-in-a-directory-with-over-200-000-f http://stackoverflow.com/questions/349251/how-do-i-find-out-how-many-files-are-in-a-directory – JohnFx Aug 05 '09 at 20:45

4 Answers4

13

That's probably about as good as it gets, but you should use GetFileSystemInfos() instead which will give you both files and directories:

_directoryInfo.GetFileSystemInfos().Length
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
2
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");

then just take the size of the filePaths array

code from: C#-Examples

Tom Neyland
  • 6,860
  • 2
  • 36
  • 52
2

You could use the GetFileSystemEntries method found in the Directory class and then query the Length of the array of items returned.

jussij
  • 10,370
  • 1
  • 33
  • 49
1
DirectoryInfo d = new DirectoryInfo(@"C:\MyDirectory\");
FileInfo[] files = d.GetFiles("*.*");

int NumberOfFilesInDir;

foreach( FileInfo file in files )
{
   NumberOfFilesInDir++;
}
jay_t55
  • 11,362
  • 28
  • 103
  • 174