tags:

views:

171

answers:

4

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.

+10  A: 

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
I will try that. Thanks.
Silv3rSurf
+1  A: 
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");

then just take the size of the filePaths array

code from: C#-Examples

instanceofTom
Sean Brights answer probably works better for your code
instanceofTom
A: 

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

jussij
A: 
DirectoryInfo d = new DirectoryInfo(@"C:\MyDirectory\");
FileInfo[] files = d.GetFiles("*.*");

int NumberOfFilesInDir;

foreach( FileInfo file in files )
{
   NumberOfFilesInDir++;
}
baeltazor
Why not just do files.Length?
David Hodgson
I'm a self taught programmer and have not used that way before. I wasn't trying to imply that the original answer wasn't good, I was simply offering another way... :-)
baeltazor