Link to home
Start Free TrialLog in
Avatar of jamesh1031
jamesh1031Flag for United States of America

asked on

How to automatically delete files older than X in a folder

We have a .net program and we create various log files and want to delete them after a certain amount of time. What is the best way to do this?
Avatar of kaufmed
kaufmed
Flag of United States of America image

You can loop through the directory and check the time against a target value. For example, if you wanted to delete those older than 30 days, you could use:
public static void PurgeDirectory(string path)
{
    System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(path);
    DateTime targetDate = DateTime.Now.AddDays(-30);

    foreach (System.IO.FileInfo fi in info.GetFiles())
    {
        if (fi.LastAccessTime > targetDate)
        {
            fi.Delete();
        }
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial