C# to delete files older than X days from a directory

The vast majority of the time, when I build an integration I archive all the files so that they can be used to track down where something is going wrong.  Unfortunately if left unchecked these files can grow and grow and it becomes impossible (or rather terribly difficult) to sort through the files to see if there was indeed an issue.  The answer to this is to cull down the files when you archive them.  To this end it’s good to kill all files older than X days.  This is a console application that can do this, it actually does this in 3 directories.  Path, path1 and path2 define the directories and days is the amount of days back to delete.

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

namespace TestConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string path, path2, path3;
int days;
System.DateTime date;
System.DateTime keepdate;
path = "Y:\\SQL_Backups\\SFDC_Data";
path2 = "Y:\\SQL_Backups\\TaleoData";
path3 = "Y:\\SQL_Backups\\dnn5_test";
days = 10;
date = (DateTime.Now);
keepdate = date.AddDays(-days);

DirectoryInfo fileListing = new DirectoryInfo(@path);

foreach (FileInfo f in fileListing.GetFiles())

{
if (f.LastWriteTime <= keepdate)
f.Delete();
}

DirectoryInfo fileListing2 = new DirectoryInfo(@path2);

foreach (FileInfo f in fileListing2.GetFiles())
{
if (f.LastWriteTime <= keepdate)
f.Delete();
}

DirectoryInfo fileListing3 = new DirectoryInfo(@path3);

foreach (FileInfo f in fileListing3.GetFiles())
{
if (f.LastWriteTime <= keepdate)
f.Delete();
}

}
}
}

I have yet to get this functionality to work in SSIS but will post how to do that once I figure it out.

Comments are closed.