Reputation: 323
I need to check to see if a directory is empty. The problem is, I want to consider the directory empty if it contains a sub folder regardless of whether or not the sub folder contains files. I only care about files in the path I am looking at. This directory will be accessed across the network, which kind of complicates things a bit. What would be the best way to go about this?
Upvotes: 14
Views: 30897
Reputation: 54877
The Directory.EnumerateFiles(string)
method overload only returns files contained directly within the specified directory. It does not return any subdirectories or files contained therein.
bool isEmpty = !Directory.EnumerateFiles(path).Any();
The advantage of EnumerateFiles
over GetFiles
is that the collection of files is enumerated on-demand, meaning that the query will succeed as soon as the first file is returned (thereby avoiding reading the rest of the files in the directory).
Upvotes: 36