系统.堆栈溢出异常,同时解析目录结构



im试图实现的是,通过解析文件来获取特定驱动器或文件夹结构中所有文件的列表。该代码在大多数驱动器和文件夹中运行良好,但在某些情况下,如Windows Drive(C:),会抛出System.StackOverflow EXception。可能是什么问题?有没有更好的方法?

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);
            }
        }            
    }
}

您是否尝试过使用调试器逐步执行以查看发生了什么?

听起来像递归,也许某处有一个指向更高级别的NTFS交汇点。

根据 MSDN,StackOverflowException 的定义是

执行堆栈溢出时引发的异常 因为它包含太多嵌套方法调用。此类不能 继承。

所以这就是我猜测的原因。系统上的目录结构不太可能比执行堆栈允许的调用次数更深。

最新更新