Tharkis
Tharkis

Reputation: 323

Check to see if directory has no files, but it may contain subfolders

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

Answers (2)

ispiro
ispiro

Reputation: 27633

Perhaps this:

if (Directory.GetFiles(path).Length == 0)...... ;

Upvotes: 10

Douglas
Douglas

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

Related Questions