public class RecursiveFileSearch
{
static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();
static void Main()
{
// 检测逻辑盘符
string[] drives = System.Environment.GetLogicalDrives();
foreach (string dr in drives)
{
System.IO.DriveInfo di = new System.IO.DriveInfo(dr);
//跳过没有就绪的盘
if (!di.IsReady)
{
Console.WriteLine("The drive {0} could not be read", di.Name);
continue;
}
System.IO.DirectoryInfo rootDir = di.RootDirectory;
WalkDirectoryTree(rootDir);//递归
}
// 未能成功浏览的文件(权限不够等原因)
Console.WriteLine("拒绝访问的有:");
foreach (string s in log)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;
//遍历目录下的所有文件夹
try
{
files = root.GetFiles("*.*");
}
//拒绝访问导致的异常
catch (UnauthorizedAccessException e)
{
log.Add(e.Message);
}
//文件残缺
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
if (files != null)
{
foreach (System.IO.FileInfo fi in files)
{
//打印本目录下所有文件名(不含文件夹)
Console.WriteLine(fi.FullName);
}
// 获取子文件夹集合
subDirs = root.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
//递归调用本方法应用于于子文件夹
WalkDirectoryTree(dirInfo);
}
}
}
}
复制代码
递归方法很简洁,但如果目录树很大且嵌套很深,则有可能会引起堆栈溢出异常。