Delete Old Files


I was just trying to get some backups configured and I wanted a way of deleting files from a directory stucture that were older than a certain date. I couldn't figure out how to do it easier from a Windows 2003 command script, so I wrote a quick C# console app to do the job. I've included the code and a copy in case you find this useful. WARNING: Use this at your own risk, as I wrote this for myself I haven't spent any time putting in "Are You Sure" prompts or anything. If you were to do something crazy like DeleteOldFiles 5 c:\ it will delete any file on your C:\ drive that has not been written to in 5 days - including things in the Windows directory..

Update: The second I posted this, I noticed the ForFiles command in the Windows Server 2003 resource kit that works a bit like find on unix. Hey ho, at least I wrote some C# code today.

The code is below, as you can see there is not a lot to it - but a nice example of recursion.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace DeleteOldFiles
    public class DeleteOldFiles
        private static double fileCount = 0;

        static void Main(string[] args)
            double daysOld;
            if (args.Length != 2
                || !double.TryParse(args[0], out daysOld)
                || !Directory.Exists(args[1]))

            deleteOldFiles(args[1], daysOld);

        static private void deleteOldFiles(string path, double daysOld)
                  String.Format("Deleting files older than {0} days"
            deleteOldFiles(path, DateTime.Now.AddDays(-daysOld));
                  String.Format("{0} files deleted"

        static private void deleteOldFiles (string path, DateTime olderThanDate)
            DirectoryInfo dirInfo = new DirectoryInfo(path);

            FileInfo[] files = dirInfo.GetFiles();
            foreach (FileInfo file in files)
                if (file.LastWriteTime < olderThanDate)
                          String.Format("Delete {0}.",file.FullName)
                    file.IsReadOnly = false;

            // Now recurse down the directories
            DirectoryInfo[] dirs = dirInfo.GetDirectories();
            foreach (DirectoryInfo dir in dirs)
                deleteOldFiles(dir.FullName, olderThanDate);

        static private void displayUsage()
            string message = "DeleteOldFiles.\n\n"
                           + "Console utility to recursively search a directory and\n"
                           + "delete files older than a certain number of days.\n\n"
                           + "Usage: DeleteOldFiles daysOld path\n\n"
                           + "\tdaysOld\tnumber of days old the file must be over to be deleted\n\n"
                           + "\tpath\tlocation on file system that you want to recursively search\n\n";


Download file and source


Ah, pity you're not using OS X - you could use Automator at a fraction of the effort, and even use it to create plug-ins to other apps ;-)

Actually, that reminds me of my old job. I'd set up a CVS repository, and one guy on the team was a dimwit, and kept on checking in stuff he shouldn't. He was continually asking me to get rid of it, and it started to p*ss me off. He came over one day after doing the same thing twice in one morning, so I SSHd to the box and went to clear the new directory he'd created, using:

rm -rf /home/cvsroot/project/spanner

unfortunately (and I don't know why I typed the full path in anyway - saved doing a cd I guess) I actually typed:

rm -rf / home/cvsroot/project/spanner

(note the space!)

I realised my mistake when pages of deleted files went flying past my eyes!

Thank you Martin,

Just what I was looking for. I added my logging class and popped it into my code.


Creative Commons License
This blog is licensed under a Creative Commons License.