Reputation:
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?
Upvotes: 1
Views: 5716
Reputation: 1
string nlogfolderpath = System.Web.Hosting.HostingEnvironment.MapPath("~/LogInfo");
string[] nfiles = Directory.GetFiles(nlogfolderpath);
DirectoryInfo d = new DirectoryInfo(nlogfolderpath);
foreach (string file in nfiles)
{
FileInfo fi = new FileInfo(file);
if (fi.LastAccessTime < DateTime.Now.AddDays(-3))
{
fi.Delete();
}
}
Upvotes: 0
Reputation: 25258
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.
Upvotes: 8
Reputation: 5971
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.
Upvotes: 4