下面的示例演示如何使用递归遍历目录树。递归方法很简洁,但如果目录树很大且嵌套很深,则有可能会引起堆栈溢出异常。
对于所处理的特定异常以及在每个文件和文件夹上执行的特定操作,都只是作为示例提供。您应该修改此代码来满足自己特定的需要。有关更多信息,请参见代码中的注释。
如下图所示:
附代码如下:
using System;
namespace 创建人族
{
public class RecursiveFileSearch
{
static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();
static void Main()
{
// Start with drives if you have to search the entire computer.
string[] drives = System.Environment.GetLogicalDrives();
foreach (string dr in drives)
{//去掉这个if循环,那么输出电脑所有硬盘文件名
//将d改成你需要查询的目录
if (dr.ToLowerInvariant().Contains("d") ) {
System.IO.DriveInfo di = new System.IO.DriveInfo(dr);
// Here we skip the drive if it is not ready to be read. This
// is not necessarily the appropriate action in all scenarios.
if (!di.IsReady)
{
Console.WriteLine("The drive {0} could not be read", di.Name);
System.IO.File.WriteAllText("C:\\Users\\Administrator\\Desktop\\1.txt", "The drive {0} could not be read");
continue;
}
System.IO.DirectoryInfo rootDir = di.RootDirectory;
WalkDirectoryTree(rootDir);
}
}
// Write out all the files that could not be processed.