-4

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:

   camIndex

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.

At the moment I have a timer than runs every 5 minutes to delete files that are say more than 24 hours old.

I have found that my following code is memory intensive and over a period of a few days the explorer.exe has climbed in the RAM memory.

My motion app needs to be on all the while so a low memory footprint is essential for this 'archiving'...

The following code is long and seems to me hugely inefficient. Is there a better way I can achieve my aims?

I use this code:

List<string> catDirs = Directory.EnumerateDirectories(Shared.MOTION_DIRECTORY, "*", SearchOption.TopDirectoryOnly).ToList();
for (int index = 0; index < catDirs.Count; index++)
{
   for (int camIndex = 0; camIndex < 4; camIndex++)
   {
       if (Directory.Exists(catDirs[index] + "\\Catalogues\\" + camIndex.ToString()))
       {
           List<string> years = GetDirectoryList(catDirs[index] + "\\Catalogues\\" + camIndex.ToString(), true);
           if (years.Count == 0)
           {
                Directory.Delete(catDirs[index]);
            }
            for (int yearIndex = 0; yearIndex < years.Count; yearIndex++)
            {
                DirectoryInfo diYear = new DirectoryInfo(years[yearIndex]);
                List<string> months = GetDirectoryList(years[yearIndex], true);
                if (months.Count == 0)
                {
                  Directory.Delete(years[yearIndex]);
                }
                for (int monthIndex = 0; monthIndex < months.Count; monthIndex++)
                {
                    DirectoryInfo diMonth = new DirectoryInfo(months[monthIndex]);
                    List<string> days = GetDirectoryList(months[monthIndex], true);
                    if (days.Count == 0)
                    {                          
                        Directory.Delete(months[monthIndex]);                           
                    }
                    for (int dayIndex = 0; dayIndex < days.Count; dayIndex++)
                    {
                        DirectoryInfo diDay = new DirectoryInfo(days[dayIndex]);
                        List<string> hours = GetDirectoryList(days[dayIndex], true);
                        if (hours.Count == 0)
                        {
                            Directory.Delete(days[dayIndex]);                              
                        }
                        for (int hourIndex = 0; hourIndex < hours.Count; hourIndex++)
                        {
                            DirectoryInfo diHour = new DirectoryInfo(hours[hourIndex]);
                            List<string> mins = GetDirectoryList(hours[hourIndex], false);
                            if (mins.Count == 0)
                            {
                                Directory.Delete(hours[hourIndex]);
                            }
                            for (int minIndex = 0; minIndex < mins.Count; minIndex++)
                            {
                                bool deleteMe = false;
                                DirectoryInfo diMin = new DirectoryInfo(mins[minIndex]);
                                DateTime foundTS = new DateTime(Convert.ToInt16(diYear.Name), Convert.ToInt16(diMonth.Name), Convert.ToInt16(diDay.Name),
                                Convert.ToInt16(diHour.Name), Convert.ToInt16(diHour.Name), 00);
                                double minutesElapsed = upToDateDate.Subtract(foundTS).TotalMinutes;
                               if (minutesElapsed > diff)
                               {
                                   deleteMe = true;
                               }
                               if (deleteMe)
                               {
                                   Directory.Delete(mins[minIndex], true);
                               }
                           }
                       }
                   }
               }
           }
       }
   }
22
  • 3
    That is a lot of nested for loops! Your question would be clearer if you explained exactly what the code does. What is the directory structure? How are the files named? What are you using to determine their age? Jan 6, 2015 at 20:54
  • 2
    @AndrewSimpson - Here you go: stackoverflow.com/questions/268132/… Jan 6, 2015 at 21:01
  • 1
    Really looks like nested directories by time frames. Why do you need that if you flush everything every 24 hour? Could simplify the code to 2-3 lines if you did not have to loop like that. Jan 6, 2015 at 21:03
  • 1
    @AndrewSimpson: You could simply rebuild the queue when the program starts back up. Just scan your directories and rebuild the queue. Jan 6, 2015 at 21:04
  • 1
    Don't know if this is helpful or not but you could look into File.GetCreationTime: msdn.microsoft.com/en-us/library/…
    – pcnThird
    Jan 6, 2015 at 21:05

1 Answer 1

5

This might help, not tested efficiency though:

Directory
.GetFiles(@"[Path of your root directory]", "*.*", SearchOption.AllDirectories)
.Where(item =>
{
    try
    {
        var fileInfo = new FileInfo(item);
        return fileInfo.CreationTime < DateTime.Now.AddHours(-24);
    }
    catch (Exception)
    {
        return false;
    }
})
.ToList()
.ForEach(File.Delete);

Make sure you add proper exception handling and avoid zombie try / empty catch (not recommended)

7
  • 3
    I would avoid the ToList and use a foreach loop. Jan 6, 2015 at 21:20
  • 1
    Agree, that might help saving some CPU usage especially when list goes big.
    – Jsinh
    Jan 6, 2015 at 21:22
  • 1
    With 2.2Gb worth of files (weighting 10kb each, which means a lot), enumerating them one by one will be highly, highly inefficient. That's a lot of I/O operations for a 5 minutes timeframe. I think burning stuff at the directory level was the good approach (albeit badly implemented), and should be in a much bigger timeframe. Jan 6, 2015 at 21:22
  • 1
    The size don't matter, but the amount does. I'd maybe throw a Parallel.ForEach in there to try to speed things up a bit, if you really want to enumerate all files instead of blowing up a folder. Jan 6, 2015 at 21:30
  • 1
    @Pierre-LucPineault - Yes Parallel.ForEach would be a smart way to handle the amount of files rush - msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx (cc: Andrew Simpson)
    – Jsinh
    Jan 6, 2015 at 21:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.