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;
}
}
}
The exception is:
System.InvalidOperationException was unhandled Message="Stack empty." Source="System"
Any ideas how to fix?