Advertisement
isendrak

DirectoryDeleter

Oct 8th, 2018
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4.  
  5. class DirectoryDeleter{
  6.     public static void DeleteSubdirsOlderThan(DirectoryInfo di, TimeSpan ts){
  7.         if(!di.Exists) return;
  8.         Stack<DirectoryInfo> dirs = new Stack<DirectoryInfo>();
  9.         dirs.Push(di);
  10.         DirectoryInfo current;
  11.         while(dirs.Count > 0){
  12.             current = dirs.Pop();
  13.             try{
  14.                 foreach(DirectoryInfo subdir in current.GetDirectories()){
  15.                     if((DateTime.Now - subdir.CreationTime) > ts){
  16.                         try{
  17.                             subdir.Delete(true);
  18.                         }
  19.                         catch(UnauthorizedAccessException){
  20.                             Console.Error.WriteLine("Access denied: \"{0}\"", subdir.FullName);
  21.                         }
  22.                         catch(DirectoryNotFoundException){
  23.                             Console.Error.WriteLine("Directory not found: \"{0}\"", subdir.FullName);
  24.                         }
  25.                         catch(IOException){
  26.                             Console.Error.WriteLine("Directory is read-oly: \"{0}\"", subdir.FullName);
  27.                         }
  28.                     }
  29.                     else{
  30.                         dirs.Push(subdir);
  31.                     }
  32.                 }
  33.             }
  34.             catch(UnauthorizedAccessException){}
  35.         }
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement