I have to check, if directory on disk is empty. It means, that it does not contain any folders/files. I know, that there is a simple method. We get array of FileSystemInfo\'
You could try Directory.Exists(path)
and Directory.GetFiles(path)
- probably less overhead (no objects - just strings etc).
Here is something that might help you doing it. I managed to do it in two iterations.
private static IEnumerable<string> GetAllNonEmptyDirectories(string path)
{
var directories =
Directory.EnumerateDirectories(path, "*.*", SearchOption.AllDirectories)
.ToList();
var directoryList =
(from directory in directories
let isEmpty = Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).Length == 0
where !isEmpty select directory)
.ToList();
return directoryList.ToList();
}
Since you are going to work with a DirectoryInfo object anyway, I'd go with an extension
public static bool IsEmpty(this DirectoryInfo directoryInfo)
{
return directoryInfo.GetFileSystemInfos().Count() == 0;
}
If you don't mind leaving pure C# and going for WinApi calls, then you might want to consider the PathIsDirectoryEmpty() function. According to the MSDN, the function:
Returns TRUE if pszPath is an empty directory. Returns FALSE if pszPath is not a directory, or if it contains at least one file other than "." or "..".
That seems to be a function which does exactly what you want, so it is probably well optimised for that task (although I haven't tested that).
To call it from C#, the pinvoke.net site should help you. (Unfortunately, it doesn't describe this certain function yet, but you should be able to find some functions with similar arguments and return type there and use them as the basis for your call. If you look again into the MSDN, it says that the DLL to import from is shlwapi.dll
)
My code is amazing it just took 00:00:00.0007143 less than milisecond with 34 file in folder
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
bool IsEmptyDirectory = (Directory.GetFiles("d:\\pdf").Length == 0);
sw.Stop();
Console.WriteLine(sw.Elapsed);
There is a new feature in Directory
and DirectoryInfo
in .NET 4 that allows them to return an IEnumerable
instead of an array, and start returning results before reading all the directory contents.
public bool IsDirectoryEmpty(string path)
{
IEnumerable<string> items = Directory.EnumerateFileSystemEntries(path);
using (IEnumerator<string> en = items.GetEnumerator())
{
return !en.MoveNext();
}
}
EDIT: seeing that answer again, I realize this code can be made much simpler...
public bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}