You've also stumbled (or will do shortly) on a problem I came across just recently.
If you try to enumerate across a file or folder that you don't have permissions on the EnumerateDirectories
or EnumerateFolders
method will simply stop and throw an exception.
Trapping the exception will also cause it to stop. This is almost certainly not the behaviour you want.
I found a recursive solution on here and implemented a method on this SO page called FindAccessableFiles
(I think it might be the last incarnation) and it works extremely well.
private static IEnumerable<String> FindDeletableFolders(string path, string file_pattern, bool recurse)
{
IEnumerable<String> emptyList = new string[0];
if (File.Exists(path))
return new string[] { path };
if (!Directory.Exists(path))
return emptyList;
var top_directory = new DirectoryInfo(path);
// Enumerate the files just in the top directory.
var files = top_directory.EnumerateFiles(file_pattern).ToList();
var filesLength = files.Count();
var filesList = Enumerable
.Range(0, filesLength)
.Select(i =>
{
string filename = null;
try
{
var file = files.ElementAt(i);
filename = file.Name; // add your date check here }
catch (FileNotFoundException)
{
}
catch (UnauthorizedAccessException)
{
}
catch (InvalidOperationException)
{
// ran out of entries
}
return filename;
})
.Where(i => null != i);
if (!recurse)
return filesList;
var dirs = top_directory.EnumerateDirectories("*");
var dirsLength = dirs.Count();
var dirsList = Enumerable
.Range(0, dirsLength)
.SelectMany(i =>
{
string dirname = null;
try
{
var dir = dirs.ElementAt(i);
dirname = dir.FullName;
if (dirname.Length > 0)
{
var folderFiles = FindDeletableFolders(dirname, file_pattern, recurse).ToList();
if (folderFiles.Count == 0)
{
try
{
Directory.Delete(dirname);
}
catch
{
}
}
else
{
return folderFiles;
}
}
}
catch (UnauthorizedAccessException)
{
}
catch (InvalidOperationException)
{
// ran out of entries
}
return emptyList;
});
return Enumerable.Concat(filesList, dirsList).ToList();
}
I had to hack some of my code out so check the function and test it before use.
The code will return a list of folders that can be deleted and also delete empty folders it comes across.