Using .NET 3.0, I’ve got the method below which correctly returns a collection of all of the files and directories (and sub-directories) of a specified directory. I’d like to, if possible, dumb this down to only use constructs that I’m pretty comfortable with. Specifically, here are the things I’m not clear on:
1. IEnumerable<FileSystemInfo>: I'd like to return List<FileSystemInfo> instead
2. Stack<FileSystemInfo>: I'd list to use List<FileSystemInfo> instead.
3. yield return: I've never used this before
.
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 argument could be made that I should just get comfortable with the code above, but that’s not what I’m shooting for today.
Thanks in advance
I believe you’re looking for the existing method GetFileSystemInfos(string, SearchOptions). If you specify AllDirectories as the SearchOptions value it will recursively search the passed in folder.
For Example:
If you want to write it out the long way though you can do the following