我一直用它来删除空文件夹,它完全符合我的需要。如果文件夹只包含 SINGLE .txt文件,我需要添加一个规则来删除该文件夹。如果仅包含.txt文件,我该如何更改此语法仍然删除该目录?
static void Main(string[] args)
{
string path = @"C:\Test\";
}
public static void processDirectory(string startLocation)
{
foreach (var directory in Directory.GetDirectories(startLocation))
{
processDirectory(directory);
if (Directory.GetFiles(directory).Length == 0 && Directory.GetDirectories(directory).Length == 0)
{
Directory.Delete(directory, false);
}
}
}
修改
这会产生语法错误,但我认为这是我想要完成的事情
if (Directory.GetFiles(Path.GetExtension) == ".txt")
答案 0 :(得分:-2)
这样的东西?
public static void processDirectory(string startLocation)
{
foreach (var directory in Directory.GetDirectories(startLocation))
{
processDirectory(directory);
var aFiles = Directory.GetFiles(directory);
var noFiles = aFiles.Length == 0 || (aFiles.Length == 1 && aFiles.Count(file => Path.GetExtension(file) == ".txt") == 1);
if (noFiles && Directory.GetDirectories(directory).Length == 0)
{
Directory.Delete(directory, true);
}
}
}
更新:OP修改了问题以指定SINGLE文件。修改答案以匹配。