我正在进行一个控制台项目,其目标是在整个磁盘上搜索扩展名为“.config”的所有文件。
我尝试过以下方式:
foreach (string file in Directory.GetFiles("C:\\", "*.config", SearchOption.AllDirectories))
{
Console.WriteLine(file);
Console.ReadLine();
}
但是出现了“拒绝访问路径(...)”的错误。
在互联网上,我找到了这段代码:
Stack<string> pending = new Stack<string>();
pending.Push("C:\\");
while (pending.Count != 0)
{
var path = pending.Pop();
string[] next = null;
try
{
next = Directory.GetFiles(path, "*.config");
}
catch { }
if (next != null && next.Length != 0)
foreach (var file in next)
{
Console.WriteLine(file);
Console.ReadLine();
}
try
{
next = Directory.GetDirectories(path);
foreach (var subdir in next) pending.Push(subdir);
}
catch { }
}
但它只会在“回车”键上单击显示路径,我想将这些文件/路径保存在列表中。有人可以帮忙吗?
Console.ReadLine();
。将此行替换为myList.Add(file)
,然后您应该就完成了。如果您写:“将它们保存在列表中”,那么您至少应该有一个列表来保存它们;) - Mong Zhu