Recursion is cool.. but you have to look out for your stack... You can easily cause a stack overflow. Now on 32 and 64bit OS's the chance of it happening is remote but it can still happen.
just a simple template for recursive functions in C#
Code: Select all
public object Recursive(object value)
{
object result;
result = (new Random()).Next(1, 100);
foreach(object o in objects)
{
result += Recursive(o);
}
return result;
}
Quick and dirty way of getting past the obstacle. Then you can actually use the result rather than just have it printed to the console.
Code: Select all
public static System.Collections.ArrayList SearchEmptyFolders(System.IO.DirectoryInfo baseFolder)
{
System.Collections.ArrayList result = new ArrayList();
try
{
System.IO.FileInfo[] fileList = baseFolder.GetFiles();
if (fileList.Length == 0)
{
result.Add(baseFolder.FullName);
}
System.IO.DirectoryInfo[] subFolders = baseFolder.GetDirectories();
foreach (System.IO.DirectoryInfo subfolder in subFolders)
{
result.AddRange(SearchEmptyFolders(subfolder));
}
}
catch (UnauthorizedAccessException) {}
return result;
}
Bladerunner wrote:But slapping a try catch within the foreach will work very well.
No it won't as the exception is on the current folder not on the children. You get it from
Code: Select all
System.IO.FileInfo[] fileList = baseFolder.GetFiles();
or
Code: Select all
System.IO.DirectoryInfo[] subFolders = baseFolder.GetDirectories();
but the exception is still for the current folder. As such it won't even get to the loop.