我试图实现的是,通过解析文件来获取特定驱动器或文件夹结构中所有文件的列表。我还试图处理在受保护文件的情况下发生的未经授权的异常。代码在大多数情况下都可以正常工作驱动器和文件夹,但在某些情况下,如 Windows 驱动器(C:),抛出 System.StackOverflow 异常。可能是什么问题?有更好的方法吗?
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);
}
}
}
}