zoukankan      html  css  js  c++  java
  • 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         //}
  • 相关阅读:
    Volatile关键字
    ThreadPoolExecutor线程池基本原理及使用
    HashMap线程不安全源码解析(1.7 + 1.8)
    SpringBoot+ajax+formData实现图片上传和回显
    BloomFilter
    POST和GET
    快手电话面试
    Apache SSI 远程命令执行漏洞
    SYSTEM--服务器提权
    封神台靶场练习(2)
  • 原文地址:https://www.cnblogs.com/sclu/p/13065820.html
Copyright © 2011-2022 走看看