Thread: Newbie Question about deleting old files from a folder

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    77

    Newbie Question about deleting old files from a folder

    Hi I am new to c# and trying to learn. I have written this code to delete files from a folder older then 30 days. I think there is something seriously wrong with my logic. It deletes any new files as well. Thanks for any help

    Code:
    static void Main(string[] args)
            {
               
               DateTime timenow = System.DateTime.Now;
               DateTime timeminus = timenow.AddDays(-30);
    
                    string[] files = Directory.GetFiles(@"c:\temp\");
                   DateTime time = Directory.GetCreationTime(@"c:\temp\");
    
    
                   foreach (string file in files)
                       if (time < timeminus)
                           File.Delete(file);
                       else
                           break;
                      
    
                        
                    }

  2. #2
    Registered User
    Join Date
    Mar 2009
    Location
    england
    Posts
    209
    Code:
    static void Main(string[] args)
    {
        String[] files = Directory.GetFiles("c:\\path");
        DateTime delete_time = DateTime.Now.AddDays(-30);
    
        foreach (String f in files)
            if (File.GetCreationTime(f) < delete_time)
                File.Delete(f);
    }
    The way you were doing it, you were looping the files but always comparing your cut-off time against the folder's creation time.

    The way I did it, I loop the files comparing the cut-off time against the file's creation time.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    77
    Thanks a lot for your help. I tried your version of the script but it doesn't delete the files at all. I get no error. Any ideas? Thanks!!!

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    77
    Sorry my fault it works like a charm. Thanks for your help. I will study the code

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    77
    I also want it to go into subfolders to delete old files. But let me try that first if I fail I will ask. Thanks again for your help

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Deleting contents of a folder
    By Tjm7777 in forum C Programming
    Replies: 8
    Last Post: 04-14-2009, 07:40 AM
  2. Creating and deleting directories and deleting files
    By fguy817817 in forum C Programming
    Replies: 1
    Last Post: 04-08-2009, 07:26 AM
  3. deleting a folder AND copying a folder
    By hanhao in forum C++ Programming
    Replies: 2
    Last Post: 05-01-2004, 08:48 AM
  4. Newbie question about registries/files
    By SirDavidGuy in forum C++ Programming
    Replies: 1
    Last Post: 02-20-2002, 09:58 PM
  5. Replies: 12
    Last Post: 01-23-2002, 07:56 PM