星期三, 3月 17, 2010

FileSystemWalker

用 foreach 以遞迴方式去找出所有檔案根目錄,順便練習 yield。


class FileSystemWalker
{
private string _path = "";
public FileSystemWalker(string path)
{
_path = path;
}

public IEnumerable<FileSystemInfo> Walk()
{
foreach( string d in Directory.GetDirectories( _path ) )
{
DirectoryInfo di = new DirectoryInfo( d );
yield return di;
FileSystemWalker walker = new FileSystemWalker(Path.Combine(_path, d));
foreach (FileSystemInfo fsi in walker.Walk())
yield return fsi;
}
foreach (string f in Directory.GetFiles( _path ) )
{
FileInfo fi = new FileInfo(f);
yield return fi;
}
}
}

class Program
{
static void Main(string[] args)
{
foreach(FileSystemInfo fsi in new FileSystemWalker(@"f:\").Walk())
{
if( fsi.Attributes == FileAttributes.Directory )
Console.WriteLine( "[D]{0}", fsi.FullName );
else
Console.WriteLine("[F]{0}", fsi.FullName);
}
Console.ReadLine();
}
}

沒有留言:

您或許對這些文章有興趣

Related Posts Plugin for WordPress, Blogger...