c# winform定时器,删除文件/文件夹

在程序运行时,需要自动删除一些文件,以免硬盘占满。

下列程序自动删除文件/文件夹。

首先从工具箱拖入一个Timer,设置Enabled为True,interval为发生的间隔,事件Tick为要发生的事件。

 1         private void timer1_Tick(object sender, EventArgs e) //每隔一段时间触发该函数。
 2         {
 3             DeleteFile("D:/test", 7);  //删除该目录下 超过 7天的文件
 4             DeleteDirectory("D:/test",7)//删除目录下超过7天的文件夹
 5         }
 6         private void DeleteFile(string fileDirect, int saveDay)
 7         {
 8             DateTime nowTime = DateTime.Now;
 9             string[] files = Directory.GetFiles(fileDirect, "*.*", SearchOption.AllDirectories);  //获取该目录下所有文件    
10             foreach (string file in files)
11             {
12                 FileInfo fileInfo = new FileInfo(file);
13                 TimeSpan t = nowTime - fileInfo.CreationTime;  //当前时间  减去 文件创建时间               
14                 int day = t.Days;
15                 if (day > saveDay)   //保存的时间 ;  单位:天                
16                 {
17                     File.Delete(file);  //删除超过时间的文件                
18                 }
19             }
20         }
21         //private void DeleteDirectory(string fileDirect, int saveDay)
22         //{
23         //    DateTime nowTime = DateTime.Now;
24         //    DirectoryInfo root = new DirectoryInfo(fileDirect);
25         //    DirectoryInfo[] dics = root.GetDirectories();//获取文件夹
26 
27         //    FileAttributes attr = File.GetAttributes(fileDirect);
28         //    if (attr == FileAttributes.Directory)//判断是不是文件夹
29         //    {
30         //        foreach (DirectoryInfo file in dics)//遍历文件夹
31         //        {
32         //            TimeSpan t = nowTime - file.CreationTime;  //当前时间  减去 文件创建时间
33         //            int day = t.Days;
34         //            if (day > saveDay)   //保存的时间 ;  单位:天
35         //            {
36 
37         //                Directory.Delete(file.FullName, true);  //删除超过时间的文件夹
38         //            }
39         //        }
40 
41         //    }
42         //}
原文地址:https://www.cnblogs.com/sclu/p/13065820.html