static List<string> CalculateDirectoryContents(string root)
{
var result = new List<string>();
// Data structure to hold names of subfolders to be
// examined for files.
var dirs = new Stack<string>();
if (!Directory.Exists(root))
{
throw new ArgumentException();
}
dirs.Push(root);
while (dirs.Any())
{
string currentDir = dirs.Pop();
var di = new DirectoryInfo(currentDir);
result.Add(di.Name);
string[] subDirs;
try
{
subDirs = Directory.GetDirectories(currentDir);
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file. It may or may not be acceptable
// to ignore the exception and continue enumerating the remaining files and
// folders. It is also possible (but unlikely) that a DirectoryNotFound exception
// will be raised. This will happen if currentDir has been deleted by
// another application or thread after our call to Directory.Exists. The
// choice of which exceptions to catch depends entirely on the specific task
// you are intending to perform and also on how much you know with certainty
// about the systems on which this code will run.
catch (UnauthorizedAccessException e)
{
Logger.WriteError(e.Message);
continue;
}
catch (DirectoryNotFoundException e)
{
Logger.WriteError(e.Message);
continue;
}
string[] files;
try
{
files = Directory.GetFiles(currentDir);
}
catch (UnauthorizedAccessException e)
{
Logger.WriteError(e.Message);
continue;
}
catch (DirectoryNotFoundException e)
{
Logger.WriteError(e.Message);
continue;
}
foreach (var file in files)
{
try
{
var fi = new FileInfo(file);
result.Add(fi.Name);
result.Add(File.ReadAllText(file));
}
catch (IOException e)
{
Logger.WriteError(e.Message);
}
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
// push in reverse order
for (var i = subDirs.Length - 1; i >= 0; i--)
{
dirs.Push(subDirs[i]);
}
}
return result;
}