Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find out how many files are in a directory?

Tags:

c#

.net

file-io

I need to get a count of the number of files in a directory. I could get the names of all the files in the directory using System.IO.Directory.GetFiles() and take the length of that array but that takes too long on large directories. Is there a way to get just the count without having to get the names?

like image 930
Simon Avatar asked Dec 08 '08 11:12

Simon


People also ask

How do I list the number of files in a directory in Windows?

Browse to the folder containing the files you want to count. Highlight one of the files in that folder and press the keyboard shortcut Ctrl + A to highlight all files and folders in that folder. In the Explorer status bar, you'll see how many files and folders are highlighted, as shown in the picture below.

How do you get files count in a directory in Linux?

The easiest way to count files in a directory on Linux is to use the “ls” command and pipe it with the “wc -l” command. The “wc” command is used on Linux in order to print the bytes, characters or newlines count. However, in this case, we are using this command to count the number of files in a directory.

How can I see the details of a directory?

To display the current directory content in the Linux/Unix system, we use the ls command as shown in below. Here, we will display the list contents of a directory in long listing format as well as the author of each file, date, and owner permission using -l option with the ls command in the Linux system.


1 Answers

I don't believe so, no - at least not in vanilla .NET. I suspect it's not the actual fetching of the names that takes the time - it's the OS walking through the directory internals. There may be a Win32 call you could make via P/Invoke.

How large is the directory you're looking at? In general it's at least traditionally not been a good idea to have more than a few hundred files in a directory. File systems have improved at this in general, but I don't know what the current state is with NTFS and Fat32.

like image 185
Jon Skeet Avatar answered Oct 01 '22 07:10

Jon Skeet