views:

253

answers:

2

Hi,

I would like to run a timer for every 5 hours and delete the files from the folder older than 4 days. Could you please with sample code?

Thank you..

+5  A: 
            DateTime CutOffDate = DateTime.Now.AddDays(-4)
            DirectoryInfo di = new DirectoryInfo(folderPath);
            FileInfo[] fi = di.GetFiles();

            for (int i = 0; i < fi.Length; i++)
            {
                if (fi[i].LastWriteTime < CutOffDate)
                {
                    File.Delete(fi[i].FullName);
                }
            }

You can substitute LastWriteTime property for something else, thats just what I use when clearing out an Image Cache in an app I have.

EDIT:

Though this doesnt include the timer part... I'll let you figure that part out yourself. A little Googling should show you several ways to do it on a schedule.

Neil N
Thanks Neil for the code. This is what I am looking for.
+2  A: 

Since it hasn't been mentioned, I would recommend using a System.Threading.Timer for something like this. Here's an example implementation:

    System.Threading.Timer DeleteFileTimer = null;

    private void CreateStartTimer()
    {

        TimeSpan InitialInterval = new TimeSpan(0,0,5);
        TimeSpan RegularInterval = new TimeSpan(5,0,0);

        DeleteFileTimer = new System.Threading.Timer(QueryDeleteFiles, null, 
            InitialInterval, RegularInterval);

    }

    private void QueryDeleteFiles(object state)
    {

        //Delete Files Here... (Fires Every Five Hours).
        //Warning: Don't update any UI elements from here without Invoke()ing
        System.Diagnostics.Debug.WriteLine("Deleting Files...");
    }

    private void StopDestroyTimer()
    {
        DeleteFileTimer.Change(System.Threading.Timeout.Infinite,
            System.Threading.Timeout.Infinite);

        DeleteFileTimer.Dispose();
    }

This way, you can run your file deletion code in a windows service with minimal hassle.

Robert Venables
Thanks for your suggestion. When do I have to use the StopDestroyTimer()?
Simply call when you want the timer to stop or when your service/application is shutting down. The most important thing is calling it sometime - (System.Threading.)Timer implements IDisposable so the call to Dispose() is needed.
Robert Venables
Thanks again. I got it.