我想每 5 小时运行一次计时器,并从文件夹中删除超过 4 天的文件。您能提供示例代码吗?
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);
}
}
您可以将
LastWriteTime
属性替换为其他属性,这正是我在清除应用程序中的图像缓存时使用的。
编辑:
虽然这不包括计时器部分...我会让你自己弄清楚这部分。稍微谷歌一下就可以告诉你几种按计划完成任务的方法。
由于没有提到,我建议使用
System.Threading.Timer
来做这样的事情。这是一个示例实现:
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();
}
这样,您就可以在 Windows 服务中以最小的麻烦运行文件删除代码。
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();
}
else
{
}
}