Reputation: 7324
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
Upvotes: 3
Views: 666
Reputation: 460138
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));
Upvotes: 2
Reputation: 120450
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
Upvotes: 2