我个人觉得很难避免递归。因为文件系统没有被索引。Google 桌面或 Microsoft 桌面搜索为所有文件编制了索引。如果您在那里查询,您将很快得到答案。
我们的选择是 .net 框架为您执行递归,或者您自己执行。
其他选项是 Linq - 我猜 .net 框架会进行递归。但它会更干净
林克
http://msdn.microsoft.com/en-us/library/bb882649.aspx
// Take a snapshot of the file system.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
// This method assumes that the application has discovery permissions
// for all folders under the specified path.
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
string searchTerm = @"Visual Studio";
// Search the contents of each file.
// A regular expression created with the RegEx class
// could be used instead of the Contains method.
// queryMatchingFiles is an IEnumerable<string>.
var queryMatchingFiles =
from file in fileList
where file.Extension == ".htm"
let fileText = GetFileText(file.FullName)
where fileText.Contains(searchTerm)
select file.FullName;
// Execute the query.
Console.WriteLine("The term \"{0}\" was found in:", searchTerm);
foreach (string filename in queryMatchingFiles)
{
Console.WriteLine(filename);
}
.net 代码
foreach (FileInfo fi in directory.GetFiles())
{
// Console.WriteLine(@"Found file: [{0}] in directory: [{1}]", fi.Name, directory.FullName);
}
foreach (DirectoryInfo diSourceSubDir in directory.GetDirectories())
{
// Console.WriteLine(@"Sub Folder {0} found.", diSourceSubDir.FullName);
}