4
I did this routine to delete empty folders, 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 for one problem. When I have a folder with only one file .zip
inside, it deletes the Folder, because it thinks the Folder is empty. How I outline it?
Ex: I have this folder tree:
web\ws\tiss\v3\02\00
And inside the briefcase 00
, I have the file TISS.zip
. Ws folder and all its contents (subfolders) are deleted.
string[] files_new = Directory.GetFiles(path_files, "*", SearchOption.AllDirectories);
string[] folder_new = Directory.GetDirectories(path_files, "*", SearchOption.AllDirectories);
I did this function and continues to delete folders and subfolder, if at last there is only one file .zip
.
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 changed the method to this one, using DirectoryInfo
and yet I can’t get the file .zip
in the folders.
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();
}
}
}
But using this approach(DirectoryInfo
), I can get files .zip
within.
foreach(var file in new DirectoryInfo(path_files).GetFiles())
{
string s = file.Name;
}
What is the content of
folder_new
?– rubStackOverflow
u@rubStackOverflow, A list of directories. All directories from a base folder. I made an edit in the original post.
– pnet
I don’t know much about C#, but from what I’ve noticed you’re using
Directory
, Tell me what happens if you useDirectoryInfo
, thus:DirectoryInfo di = new DirectoryInfo(@"C:\MinhaPasta");


 Console.WriteLine("Search pattern AllDirectories returns:");
 foreach (var fi in di.GetFiles("*", SearchOption.AllDirectories))
 {
 Console.WriteLine(fi.Name);
 }
– Guilherme Nascimento
@Guilhermenascimento, good morning. I had to pause this part to solve a problem in the company and as soon as I return, I will test what you passed me for comment. Just a little while longer.
– pnet
@Guilhermenascimento, you practically said everything. You should use the Directoryinfo class and not the Directory. I just need to improve my method using Directoryinfo.
– pnet