I'm trying to delete folders and their contents when the folder is older than a certain date. The problem is, there could be files in the folder that are currently in use and newer than the folder date.
The following will not catch the locked files so the program fails:
FYI: targetTime = now.Add(new TimeSpan(-12, 0, 0))
;
try {
if(modification >= targetTime) {
Directory.Delete(dir, true);
}
} catch(IOException) {
// do nothing
}
The following works but seems like a lot of extra work when catching an exception should work.
string[] dirs = Directory.GetDirectories(tempPath, "*", SearchOption.TopDirectoryOnly);
foreach(string dir in dirs) {
bool newFile = false;
DateTime modification = File.GetLastWriteTime(dir);
var file = Directory.GetFiles(dir, "*",SearchOption.AllDirectories).FirstOrDefault();
// test for newer files and directories
foreach(string testFile in files) {
DateTime foundMod = File.GetCreationTime(testFile);
if(foundMod >= targetTime) {
newFile = true;
}
else if(modification >= targetTime) {
newFile = true;
}
}
// if nothing newer is found, then nothing should be locked
if(!newFile) {
Directory.Delete(dir, true);
}
}
Is there a simpler way to catch the exception that causes Directory.Delete(dir, true); to fail when a file or folder is locked or in-use?