How do you traverse a folder structure using C# without falling into the trap of junction points?
A:
You mean you want to skip junction points? Or do you want to detect where it leads, and avoid infinite recursion?
Lasse V. Karlsen
2008-11-19 09:34:28
+6
A:
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);
}
}
Pieter Breed
2008-11-19 09:37:00
A:
you can use following code:
private void processing(string directory)
{
cmbFilesTypesSelectedIndex = cmbFilesTypes.SelectedIndex;
CheckForProjectFile(directory);
DirectoryInfo dInfo = new DirectoryInfo(directory);
DirectoryInfo[] dirs = dInfo.GetDirectories() ;
foreach (DirectoryInfo subDir in dirs)
{
CheckForProjectFile(subDir.FullName);
processing(subDir.FullName);
}
}
private void CheckForProjectFile(string directory)
{
Boolean flag = false;
DirectoryInfo dirInfo = new DirectoryInfo(directory);
FileInfo[] files = dirInfo.GetFiles();
//You can also traverse in files also
foreach (FileInfo subfile in files)
{
//Do you want
}
}
Nakul Chaudhary
2008-11-19 09:45:28
I don't see you checking for reparse points anywhere in that code. Therefore, you don't actually avoid the trap.
Michael Madsen
2008-11-19 09:51:31