Solved

How to automatically delete files older than X in a folder

Posted on 2010-11-30
2
391 Views
Last Modified: 2013-11-07
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?
0
Comment
Question by:jamesh1031
  • 2
2 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 34241893
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

0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 34241948
If you use the above, you should be a bit more cautious by checking that the path exists before trying to get its files:
public static void PurgeDirectory(string path)
{
    System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(path);

    if (info.Exists)
    {
        DateTime targetDate = DateTime.Now.AddDays(-30);

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

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question