简体   繁体   中英

How to efficiently delete empty directories (and empty sub-directories)

I have written a motion detection winform c# desktop app.

The motion frames are saved as individual jpegs to my hard drive.

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

Each jpeg's is under a file structure:

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

...to ensure the directories did not get too many files in each one.

The intention is for my app to be be running 24/7. The app can stop for reasons such as system reboot or that the User chooses to temporarily close it down.

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

I use this code to accomplish that:

   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 delete the 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 sub-directory (even of there are no files).

Is there a way of deleting the sub-folders automatically if empty or..?

Needless to say this has to be a low process operation because of the nature of my app.

Thanks

Yes. Use the overload that allows recursive deletion.

Directory.Delete(path, true)

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

Use the overload with a bool and pass true to delete recursively. That will also prevent the IOException that is thrown.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM