【问题标题】:System.StackOverflow Exception while Parsing through Directory Structure通过目录结构解析时出现 System.StackOverflow 异常
【发布时间】:2012-06-25 09:20:57
【问题描述】:

我试图实现的是,通过解析文件获取特定驱动器或文件夹结构中所有文件的列表。我还试图处理受保护文件时发生的未经授权的异常。代码有效在大多数驱动器和文件夹中都可以,但在某些情况下,例如 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);
            }
        }            
    }
}

【问题讨论】:

  • 如果您只想列出目录树中任意位置的所有文件,可以使用root.GetFiles("*.*", SearchOption.AllDirectories)。这样你就不需要递归了。
  • @Porges 我知道这个方法,我正在做这个过程,因为我的应用程序没有管理员权限。
  • @techno,如果你的应用没有管理员权限,如何递归解决权限问题?
  • @Ray Cheng 它不会处理受保护的文件。
  • @techno,你能用递归处理受保护的文件吗?

标签: c# .net file exception directory


【解决方案1】:

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

听起来像递归,也许有一个NTFS Junction Point指向更高的层次。

definition of a StackOverflowException according to MSDN

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

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

【讨论】:

  • 递归内的递归:)
  • 我能做些什么来解决这个问题?或者有其他方法吗?
  • 首先,确认确实如此。
  • 然后去谷歌你去。也许先读这篇文章虽然whathaveyoutried.com :)
猜你喜欢
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
相关资源
最近更新 更多