Skip to content

Instantly share code, notes, and snippets.

@Grynn
Last active October 12, 2015 04:38
Show Gist options
  • Save Grynn/3972045 to your computer and use it in GitHub Desktop.
Save Grynn/3972045 to your computer and use it in GitHub Desktop.
SafeEnumerateDirectory
struct FileNode
{
public string Name;
public bool IsDirectory;
public Exception Error;
public bool HasError { get { return this.Error!=null; } }
}
void Main()
{
var all = SafeEnumerateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
var allFilesWithoutErrors = all.Where(x => !x.HasError).Where (x => !x.IsDirectory);
allFilesWithoutErrors.Dump();
var itemsWithErrors = all.Where (x => x.HasError);
itemsWithErrors.Dump();
}
IEnumerable<FileNode> SafeEnumerateDirectory(string dir)
{
var pending = new Stack<string>();
var ret = new List<FileNode>();
pending.Push(dir);
while (pending.Any())
{
var item = pending.Pop();
try
{
var di = new DirectoryInfo(item);
var subItems = di.GetFileSystemInfos("*");
foreach (var subItem in subItems)
{
if ((subItem.Attributes & FileAttributes.Directory) != 0)
{
pending.Push(subItem.FullName);
}
else
{
ret.Add(new FileNode { Name = subItem.FullName, Error = null, IsDirectory = false });
}
}
ret.Add( new FileNode { Name = item, IsDirectory = true, Error = null } );
}
catch (Exception e)
{
ret.Add( new FileNode { Name = item, Error = e, IsDirectory = true } );
}
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment