count of files in a directory
-
Friday, November 10, 2006 3:18 PM
OK - I have the path of a directory save to a string variable.
I want to go to the directory and count the number of files located in that directory.
I do not know how to get started.
Please help. thank you
All Replies
-
Friday, November 10, 2006 3:24 PM
The documentation is your friend. A quick look revealed a Directory class with several useful static methods: GetFiles() and GetFileSystemEntries(). You will also want to discover the File class and the FileAttributes class.
Have fun.
-
Friday, November 10, 2006 4:28 PM
ok i am stuck here.
string
[] returnFiles = Directory.GetFiles(path);I donot know how to tell how many strings where returned.
Any hints?
-
Friday, November 10, 2006 4:36 PM
Give me some idea of your level with C#. These are very basic questions. If this is not course work for a class you are taking, you need to get some kind of training. At the very least, get one of the beginning books that is available and read the beginning chapters and work their exercises.
To answer your direct question, each array has a Length property that tells you how many elements it has. So returnFiles.Length is the count.
-
Friday, November 10, 2006 7:29 PM
use this:
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directry and sub directries
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length; // Will Retrieve count of all files in directry but not sub directries
int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directry and sub directries
I hope this will help!
BEst Regards,
Rizwan
-
Friday, November 10, 2006 9:16 PM
actually - 1 from the Length -
Wednesday, May 21, 2008 4:18 PMsuch an unhelpful post anomolous.. I'm glad someone else answered below.
-
Thursday, April 15, 2010 2:14 PM
Be careful if you are trying to get the count of user's folders in windows Vista or 7 as the Junction folders will throw an UnauthorizedAccess exception when you try to get the count this way. Using DirectoryInfo.GetFiles causes the same error.
If you are going to get the count of this folders you might have to traverse the tree and skip Junction folders.
Junction folders are links named the old way (My Music, My Pictures, etc) pointing to the new locations on Vista and 7.
Hope this helps somebody.

