Check if the directory contains files, but may contain subfolders

I need to check if the directory is empty. The problem is that I want to consider the directory empty if it contains a subfolder, regardless of whether the subfolder contains files. I just care about the files in the path I'm looking at. This directory will be accessible over the network, which complicates the situation a bit. What would be the best way to do this?

+7
source share
2 answers

Overloading the Directory.EnumerateFiles(string) method returns files contained directly in the specified directory. It does not return any subdirectories or files contained in it.

 bool isEmpty = !Directory.EnumerateFiles(path).Any(); 

The advantage of EnumerateFiles over GetFiles is that file collection is renamed on demand, which means that the request will be successful as soon as the first file is returned (so as to avoid reading the rest of the files into the directory).

+24
source

Perhaps it:

 if (Directory.GetFiles(path).Length == 0)...... ; 
+7
source

All Articles