问题
What im trying to achieve is,Get the list of all files in a specific drive or Folder Structure by parsing through the Files.I'm also trying to handle the Unauthorized Exception which occures in case of protected files.The Code works fine in most drives and folders but in some cases like the Windows Drive(C:),A System.StackOverflow EXception is thrown.What could be the problem?Is there a better way to do it?
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;
// First, process all the files directly under this folder
try
{
files = root.GetFiles("*.*");
}
// This is thrown if even one of the files requires permissions greater
// than the application provides.
catch (UnauthorizedAccessException e)
{
//eat
}
catch (System.IO.DirectoryNotFoundException e)
{
//eat
}
if (files != null)
{
foreach (System.IO.FileInfo fi in files)
{
Console.WriteLine(fi.FullName);
}
// Now find all the subdirectories under this directory.
subDirs = root.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
// Resursive call for each subdirectory.
WalkDirectoryTree(dirInfo);
}
}
}
}
回答1:
Have you tried stepping through with a debugger to see what is happening?
Sounds like recursion, maybe there is a NTFS Junction Point somewhere that is pointing to a higher level.
The definition of a StackOverflowException according to MSDN is
The exception that is thrown when the execution stack overflows because it contains too many nested method calls. This class cannot be inherited.
So that's why I'm guessing that. It is unlikely that your directory structure on your system is deeper than the number of calls the execution stack allows.
来源:https://stackoverflow.com/questions/11166990/system-stackoverflow-exception-while-parsing-through-directory-structure