Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory Traversal in C#

Tags:

c#

ntfs

How do you traverse a folder structure using C# without falling into the trap of junction points?

like image 848
Pieter Breed Avatar asked Nov 19 '08 09:11

Pieter Breed


1 Answers

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);
    }
}
like image 127
Pieter Breed Avatar answered Oct 21 '22 17:10

Pieter Breed