删除所有没有';我没有某个扩展名的文件
本文关键字:扩展名 文件 有没有 删除 | 更新日期: 2023-09-27 18:26:41
我使用此解决方案删除特定路径中的所有空文件夹和子目录:
static void Main(string[] args)
{
processDirectory(@"c:'temp");
}
private 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);
}
}
}
它工作得很好。但我想删除所有空文件夹,以及不空但不包含扩展名为.dvr
的文件的文件夹。
例如,我的文件夹中有以下文件:
a.log
b.log
c.dvr
d.dat
所以这个文件夹不能删除,因为它包含一个扩展名为dvr的文件。
如何过滤?(我使用GTK#,但我相信C#代码会起作用,因为这个解决方案是C#代码)
不幸的是,在IO操作中,错误处理是非常异常的。如果目录不为空,则Directory.Delete抛出IOException。所以你必须手动删除文件:
private static bool processDirectory(string startLocation)
{
bool result = true;
foreach (var directory in Directory.GetDirectories(startLocation))
{
bool directoryResult = processDirectory(directory);
result &= directoryResult;
if (Directory.GetFiles(directory, "*.dvr").Any())
{
result = false;
continue;
}
foreach(var file in Directory.GetFiles(directory))
{
try
{
File.Delete(file);
}
catch(IOException)
{
// error handling
result = directoryResult = false;
}
}
if (!directoryResult) continue;
try
{
Directory.Delete(directory, false);
}
catch(IOException)
{
// error handling
result = false;
}
}
return result;
}
我会使用Directory.EnumerateFiles来查看目录是否包含您要查找的文件。将您的代码更改为:
static void Main(string[] args)
{
processDirectory(@"c:'temp");
}
private static void processDirectory(string startLocation)
{
foreach (var directory in Directory.GetDirectories(startLocation))
{
processDirectory(directory);
if (Directory.GetDirectories(directory).Length == 0 ||
Directory.EnumerateFiles(directory, "*.dvr").Length == 0
)
{
Directory.Delete(directory, false);
}
}
}
Avitus的答案是正确的,但由于您需要它来在.NET 2.0中工作,因此您不能使用EnumerateFiles
方法,但GetFiles
可以很好地完成任务。但需要更多的代码。
示例:
static void Main(string[] args)
{
processDirectory(@"c:'temp");
}
private static void processDirectory(string startLocation)
{
foreach (var directory in Directory.GetDirectories(startLocation))
{
processDirectory(directory);
if (Directory.GetDirectories(directory).Length == 0))
{
bool delete = false;
var files = Directory.GetFiles(directory);
// This will delete the directory if it contains a file with the Extension
// of .dvr, regardless if there are other files in there. Might be something you want to change.
for (int i = 0; i < files.Length && !delete; i++)
{
delete = files[i].Extension.Equals(".dvr", StringComparison.OrdinalIgnoreCase);
}
if (delete)
{
// Recursive must be set to true in order to
// delete files and sub-directories in the folder.
// This folder will not have any sub-directories
// so it's only used to delete the files.
Directory.Delete(directory, /*recursive*/ true);
}
}
}
}
本着减少代码的精神,如果需要,可以在for
循环中移动Directory.Delete
方法调用,然后中断循环。