我有一个用于大量图像的体系结构,基于GUID构建图像文件夹:
C:\AdPictures\7e\42\1a\dc-7\3b\7-\4e\c2-9\ee\f-\f2\4c\7d\4a\32\14\
我需要进行递归删除,直到文件夹"14“到目录"7e”("AdPictures“文件夹需要保留,因为它是根目录)的文件夹是空的为止。
我发现:
Directory.Delete(folderPath, true); 但一旦使用它就会删除所有的东西。
如何实现一个方法,从底部开始删除所有空目录,并在找到树上的非空目录后停止?
我的解决方案应该使用递归。
发布于 2014-03-25 11:59:00
这里是递归方法。
DirectoryInfo dir = new DirectoryInfo(folderPath);
DeleteFolderIfEmpty(dir);
public void DeleteFolderIfEmpty(DirectoryInfo dir){
if(dir.EnumerateFiles().Any() || dir.EnumerateDirectories().Any())
return;
DirectoryInfo parent = dir.Parent;
dir.Delete();
// Climb up to the parent
DeleteFolderIfEmpty(parent);
}防止根部缺失
DirectoryInfo dir = new DirectoryInfo(folderPath);
DeleteFolderIfEmpty(dir);
public void DeleteFolderIfEmpty(DirectoryInfo dir){
if(dir.EnumerateFiles().Any() || dir.EnumerateDirectories().Any())
return;
if(dir.FullName == @"c:\folder\root")
return;
DirectoryInfo parent = dir.Parent;
dir.Delete();
// Climb up to the parent
DeleteFolderIfEmpty(parent);
}发布于 2014-03-21 23:12:06
getdirectories
这方面的基本递归模型。
void checkDIR(string Path)
{
//Path will equal AddImage right?
foreach(string childpath in Directory.GetDirectories(path))
{
//so here we are calling checkpaths for 7E GUID Directory Structure
checkpaths(childpath);
}
}
void checkpaths(string Path)
{
foreach(string childpath in Directory.GetDirectories(path))
{ //here we dig deeper
checkpaths(childpaths);//recursion
}
//the first recursion to get here will be the deepest directory
//we are now in '14'
if(there are any files)
{do what you want}
else
{
do what you need
}
}您可能需要一些标志或其他计数器和变量来测试和跟踪事物,但这是您正在寻找的。只要在checkpaths中调用delete,addimage就不会被删除
发布于 2014-03-22 00:10:33
试试这个:
var dir = "a/b/c/d";
white (true) {
If (Directory.EnumerateFiles(dir).Any() ||
Directory.EnumerateDirectories(dir).Any()) break;
Directory.Delete(dir);
dir = Path.GetDirectoryName(dir);
}如果我完全理解你的问题,这将删除所有的文件夹,直到找到一个不是空的。
编辑
只需更改如下:
var dir = "a/b/c/d";
white (!Directory.EnumerateFiles(dir).Any() &&
!Directory.EnumerateDirectories(dir).Any()) {
Directory.Delete(dir);
dir = Path.GetDirectoryName(dir);
}https://stackoverflow.com/questions/22570935
复制相似问题