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