子目录为空时,调试GetAllFilesAndDirectories方法 [英] Debugging GetAllFilesAndDirectories method, when there are empty sub-directories

查看:133
本文介绍了子目录为空时,调试GetAllFilesAndDirectories方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此方法用于获取文件,目录和子目录及其内容,除非其中一个子目录碰巧为空。

This method works to get the files, directories and sub-directories and their contents, UNLESS one of the sub-directories happens to be empty.

public static IEnumerable<FileSystemInfo> GetAllFilesAndDirectories ( string dir ) {

        DirectoryInfo dirInfo = new DirectoryInfo( dir );
        Stack<FileSystemInfo> stack = new Stack<FileSystemInfo>();

        stack.Push( dirInfo );
        while ( dirInfo != null || stack.Count > 0 ) {
            FileSystemInfo fileSystemInfo = stack.Pop();
            DirectoryInfo subDirectoryInfo = fileSystemInfo as DirectoryInfo;
            if ( subDirectoryInfo != null ) {
                yield return subDirectoryInfo;
                foreach ( FileSystemInfo fsi in subDirectoryInfo.GetFileSystemInfos() ) {
                    stack.Push( fsi );
                }
                dirInfo = subDirectoryInfo;
            } else {
                yield return fileSystemInfo;
                dirInfo = null;
            }
        }

}

例外是:

System.InvalidOperationException未处理
Message =堆栈为空。
Source = System

System.InvalidOperationException was unhandled Message="Stack empty." Source="System"

有任何解决方法吗?

推荐答案

我为您不久前问到的问题将帮助您避免这种情况,因为您将使用与此处使用的代码完全不同(并且更易于阅读)的代码。

I added another answer to the question you asked a little while ago that will help you avoid this because you'd be using a completely different (and easier to read) bit of code than what you're using here.

但是,为节省您的查找时间,请查看本文以其他方式递归读取文件/目录。

However, to save you the time of looking, check out this article for a different way to recursively read files/directories.

< a href = http://support.microsoft.com/kb/303974 rel = nofollow noreferrer> http://support.microsoft.com/kb/303974

我意识到这不是这个特定问题的答案,但是当有一个更容易解决的完美可行的解决方案时,为什么要花时间修复有问题的解决方案呢?

I realize this isn't an answer to this specific question, but why spend time fixing a solution that's buggy when there's a perfectly viable solution that's easier to deal with?

这篇关于子目录为空时,调试GetAllFilesAndDirectories方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆