How to efficiently remove empty directories (and empty subdirectories)

I wrote a c # winform annotation app for motion detection.

The motion frames are saved as separate jpegs on my hard drive.

There are 4 cameras from which I record. This is represented by a variable:

Each jpeg is in a file structure:

c: \ Year \ Month \ Day \ Hour \ Minute

... to ensure that directories don't get too many files in each one.

The purpose of my application is to run 24 hours a day. The application may stop for reasons such as rebooting the system or that the user decides to temporarily close it.

I need to delete files that are more than 24 hours old.

I am using this code to accomplish this:

   Directory
        .GetFiles(Shared.MOTION_DIRECTORY, "*.*", SearchOption.AllDirectories)
        .Where(item =>
        {
            try
            {
                var fileInfo = new FileInfo(item);
                if (fileInfo.CreationTime < DateTime.Now.AddHours(-24))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        })
        .ToList()
        .ForEach(File.Delete);

      

and then I use this to remove directories:

            Directory
          .GetDirectories(Shared.MOTION_DIRECTORY, "*.*", SearchOption.AllDirectories)
           .Where(item =>
           {
               try
               {
                   var dirInfo = new DirectoryInfo(item);
                   if (dirInfo.CreationTime < DateTime.Now.AddHours(-24) && !dirInfo.EnumerateFiles().Any())
                   {
                       return true;
                   }
                   else
                   {
                       return false;
                   }
               }
               catch (Exception)
               {
                   return false;
               }
           })
           .ToList()
           .ForEach(Directory.Delete);

      

but of course the error occurs when deleting a directory if there is a subdirectory (even if there are no files).

Is it possible to automatically delete subfolders if they are empty or ??

Needless to say, this must be a low process operation due to the nature of my application.

thank

+3


source to share


2 answers


Use the overload withbool

and pass true

to remove recursively. This will also prevent blowout IOException

.



.ForEach(f => Directory.Delete(f, true));

      

+2


source


Yes. Use an overload that allows recursive deletion.

Directory.Delete(path, true)

      



http://msdn.microsoft.com/en-us/library/fxeahc5f%28v=vs.110%29.aspx

+2


source







All Articles