C# - Delete Files Recursively [Beginner]


C# provides a ready to use method for deleting the directory including sub-directories and files:
    Directory.Delete(Path, true);
 
But this method is only useful when:
  • we are going to delete everything.
  • files are in read-write and can access mode.
Now if we want to delete the files only when:
  • they have met a specific condition (like it is older than two weeks).
  • we have to change the atribute and access mode before deletion.
public void DeleteFiles(FileSystemInfo fileSysInfo)
{     
   //can change the attribute   
   fileSysInfo.Attributes = FileAttributes.Normal;
   var dirInfo = fileSysInfo as DirectoryInfo;             
   if (dirInfo != null)
   {
        foreach (var objdirInfo in dirInfo.GetFileSystemInfos())
        {
                DeleteFiles(objdirInfo);
        }
   }
   //delete if file is older than two weeks
   if (fileSysInfo.LastWriteTimeUtc.Date < DateTime.UtcNow.Date.AddDays(-14))
   {
            fileSysInfo.Delete();
   }                             
}
 
call it like this:
if(Directory.Exists(DirPath))
{                                            
  DeleteFile(new DirectoryInfo(DirPath));
}
 
The advantage of using FileSystemInfo is that it can handle both File and Directory.

Comments