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?
Asked
Active
Viewed 5,509 times
2
-
5Is there a specific part of this you need help with? Nobody is going to simply write the code for you. – Jon B Sep 03 '09 at 15:23
2 Answers
8
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, that's 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
- 24,862
- 16
- 85
- 145
4
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.

Anatoliy Nikolaev
- 22,370
- 15
- 69
- 68

Robert Venables
- 5,943
- 1
- 23
- 35
-
-
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 Sep 03 '09 at 15:56