Cem Aytekin
Cem Aytekin

Reputation: 93

Check whether a directory contains any files

 DirectoryInfo d = new DirectoryInfo(path);

 if()   // there is a file in the directory do something.

I can get the files if there exists any, but I also have to consider the possbility that there is no file inside that subfolder path.

Upvotes: 3

Views: 11658

Answers (3)

Chris Berger
Chris Berger

Reputation: 555

If you have no files in a folder that exists, you'll get an empty collection:

exists

.

.

If the folder that you are looking for does not exist, you'll get this exception instead:

doesnotexist

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

string[] files = System.IO.Directory.GetFiles(path);
if (files.Length == 0)
    Console.WriteLine("Empty");
else
    Console.WriteLine("Not Empty");

Using EnumerateFiles

 var fileCount = Directory.EnumerateFiles(@"C:\").Count();
 if (fileCount == 0)
    Console.WriteLine("Empty");
 else
    Console.WriteLine("Not Empty");

Upvotes: 7

TheLethalCoder
TheLethalCoder

Reputation: 6744

If there are no files the following will return an empty string array:

var files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);

Upvotes: 0

Related Questions