I did this routine to delete empty folders, with no files inside.
foreach(var folder in folder_new)
{
if (Directory.Exists(folder))
{
if (Directory.GetFiles(folder, "*", SearchOption.AllDirectories).Length == 0)
{
Directory.Delete(folder, true);
}
}
}
So far beauty, except a problem. When I have a folder with only a .zip
file inside, it deletes the folder, because it thinks the folder is empty. How do I outline this?
Ex: I have this folder tree:
web\ws\tiss\v3string[] files_new = Directory.GetFiles(path_files, "*", SearchOption.AllDirectories);
string[] folder_new = Directory.GetDirectories(path_files, "*", SearchOption.AllDirectories);
And inside the 00
folder, I have the file TISS.zip
. The folder ws and all its contents (subfolders) is deleted.
private void processaDiretorio(string inicio)
{
foreach(var diretorio in Directory.GetDirectories(inicio))
{
processaDiretorio(diretorio);
if (Directory.GetFiles(diretorio).Length == 0 &&
Directory.GetDirectories(diretorio).Length == 0)
{
Directory.Delete(diretorio, false);
}
}
}
I have done this function and continue to delete folders and subfolder, if in the last there is only one file .zip
.
private void processaDiretorio(string inicio)
{
DirectoryInfo di = new DirectoryInfo(inicio);
foreach (var fi in di.GetDirectories())
{
processaDiretorio(fi.FullName);
if (fi.GetFiles().Length == 0 && fi.GetDirectories().Length == 0)
{
fi.Delete();
}
}
}
I changed the method to this one, using DirectoryInfo
and even then I can not get .zip
in folders.
foreach(var file in new DirectoryInfo(path_files).GetFiles())
{
string s = file.Name;
}
But using this approach ( DirectoryInfo
), I can get .zip
files inside.
foreach(var folder in folder_new)
{
if (Directory.Exists(folder))
{
if (Directory.GetFiles(folder, "*", SearchOption.AllDirectories).Length == 0)
{
Directory.Delete(folder, true);
}
}
}