我正在尝试使用它来删除我在使用递归的几个目录中的某些.htm文件。到目前为止它只使用一个文件夹工作正常,但我还没有找到一种方法来添加多个文件夹到代码。有没有办法可以在目录路径中添加更多目录,所以每次我希望它删除另一个目录中的文件时,我都不必一直更改代码?
namespace ConsoleApplication
{
class Deleter
{
static void Main(string[] args)
{
string directorypath = @"C:\Public\";
string[] directories = System.IO.Directory.GetDirectories(directorypath);
DeleteDirectories(directories);
}
private static void DeleteDirectories(string[] directories)
{
foreach (string directory in directories)
{
string[] files = System.IO.Directory.GetFiles(directory, "*.htm");
DeleteFiles(files);
directories = System.IO.Directory.GetDirectories(directory);
DeleteDirectories(directories);
}
}
private static void DeleteFiles(string[] files)
{
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
if (f.CreationTime < DateTime.Now)
f.Delete();
}
}
}
}
答案 0 :(得分:1)
而不是将您的可枚举(目录)设置为子目录&amp;希望以这种方式递归,创建一个名为subDirectories的新引用。所以你的foreach循环将如下所示:
...
foreach(var directory in directories)
{
string[] files = System.IO.Directory.GetFiles(directory, "*.htm");
DeleteFiles(files);
var subDirectories = System.IO.Directory.GetDirectories(directory);
DeleteDirectories(directories);
{
....