How do you traverse a folder structure using C# without falling into the trap of junction points?
For those that don't know: A junction point behaves similarly to a symbolic link for a folder on linux. The trap that is mentioned happens when you set up a recursive folder structure, like this:
given folder /a/b
let /a/b/c point to /a
then
/a/b/c/b/c/b becomes valid folder locations.
I suggest a strategy like this one. On windows you are limited to a maximum length on the path string, so a recursive solution probably won't blow the stack.
private void FindFilesRec(
string newRootFolder,
Predicate<FileInfo> fileMustBeProcessedP,
Action<FileInfo> processFile)
{
var rootDir = new DirectoryInfo(newRootFolder);
foreach (var file in from f in rootDir.GetFiles()
where fileMustBeProcessedP(f)
select f)
{
processFile(file);
}
foreach (var dir in from d in rootDir.GetDirectories()
where (d.Attributes & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint
select d)
{
FindFilesRec(
dir.FullName,
fileMustBeProcessedP,
processFile);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With