I wanted to create a simple IsEmpty(StorageFolder directory)
method that works in WinRT apps, i.e. that uses the async API. I don't see a relevant method in the documentation for the StorageFolder class, and I also haven't found anything in my searches. I'm sorry if I've missed it!
I managed to create the following method, which works:
public static async Task<bool> IsEmpty(StorageFolder directory)
{
var files = await directory.GetFilesAsync();
if (files.Count > 0)
{
return false;
}
var folders = await directory.GetFoldersAsync();
if (folders.Count > 0)
{
return false;
}
return true;
}
But... is there a cleaner way? Either native or that I could code... It should be a simple thing to check if a directory is empty, but I know I've faced problems before when simply trying to check if a directory or file exists using the async API of WinRT.
I'm also not entirely sure if the asynchronous calls to GetFilesAsync and GetFoldersAsync get every file/folder in the directory before returning, or if they can somehow only get a single item before realizing that Count will be higher than 0 (I'm thinking of lazy evaluation, like in the Haskell language, but this is C#...). If they could, I would be more at peace with this method :)
StorageFolder.GetItemsAsync(0,1) will retrieve the first file or sub-folder:
GetFilesAsync and GetFoldersAsync will return all of the files or folders. These calls don't know that you are only going to care about the count, and I doubt the compiler is smart enough to realize that and rewrite the calls to use filtered versions automatically.