Last active
October 12, 2015 04:38
-
-
Save Grynn/3972045 to your computer and use it in GitHub Desktop.
SafeEnumerateDirectory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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