Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 626
Tharkis Avatar asked Jun 17 '12 13:06

Tharkis


People also ask

How to check if a folder contains any files or folders?

You could use List folder action to check if there are any items in the specified folder, including files and folders. Then configure length () function to determine if any elements are included in Body. If the result is 0, it means that this is an empty folder, which does not contain any files and folders. Hope it helps.

How to check if a directory is empty or not?

If the length of the returned list is equal to zero then the directory is empty otherwise not. print("No files found in the directory.") print("Some files found in the directory.")

Why does the folder show empty but still has size?

This problem indicates a hidden attribute, implying that you have hidden the files and unable to view them in the folder. That’s why the folder shows empty but has size. There could be a number of reasons for this issue, which include: Malware or virus infection – the malware hides your files and makes the folder indicate empty but still has size.

How to fix “this folder is empty windows 10/11?

Here’s how to unhide files to fix this folder is empty Windows 10/11 problem: Step 1: In the Windows search field, enter “folder option” and select “File Explorer Options”. Step 2: In the “File Explorer Options” window, click on the “View” tab. Step 3: Choose “Show hidden files, folders and drives” under the “Hide files and folders” option.


2 Answers

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).

like image 137
Douglas Avatar answered Oct 24 '22 00:10

Douglas


Perhaps this:

if (Directory.GetFiles(path).Length == 0)...... ;
like image 28
ispiro Avatar answered Oct 23 '22 22:10

ispiro