Home > front end >  How can i check if a folder is empty with specific files types and then to delete the folder?
How can i check if a folder is empty with specific files types and then to delete the folder?

Time:12-26

I want to delete each folder that have no gif images files inside. i don't mind if it's having text files or any other files, if the folder/s have no gif files delete it.

var dirsRad = Directory.GetDirectories(radarImagesFolder);
            var dirsSat = Directory.GetDirectories(satelliteImagesFolder);

            if(dirsRad.Length > 0)
            {
                foreach(string dir in dirsRad)
                {
                    if(!Directory.EnumerateFileSystemEntries(dir).Any())
                    {
                        Directory.Delete(dir, true);
                    }
                }
            }

            if(dirsSat.Length > 0)
            {
                foreach (string dir in dirsSat)
                {
                    if (!Directory.EnumerateFileSystemEntries(dir).Any())
                    {
                        Directory.Delete(dir, true);
                    }
                }
            }

The problem with this code is that if in the folder/s there is a text file it will not delete the folder/s , i want that even if there are any files that are not gif type delete the folder/s

Only if the folder/s contains gif images files then keep the folder/s.

Tried the code above but the folder/s some of them have a text file inside so it's not deleting the folder/s.

CodePudding user response:

You can use this overload of the enumeration method you are using to only get files that end in .gif. If there aren't any, then delete the folder (including subdirectories and files).

This only applies to the current directory. If there are subdirectories of dirsRad with .gif files inside, they will be deleted. Exercise caution if that's not what you want.

It also assumes that a GIF file is simply identified by its lowercase extension. If you suspect you may have some GIF files that don't respect this, such as files written as .GIF, you'll have to make the method case-insensitive.

This translates to this simple change:

            if(dirsRad.Length > 0)
            {
                foreach(string dir in dirsRad)
                {
                    if(!Directory.EnumerateFileSystemEntries(dir, "*.gif").Any())
                    {
                        Directory.Delete(dir, true);
                    }
                }
            }
  • Related