/// <summary>/// 定期清除文件/// </summary>/// <param name="fileDirect">文件夹</param>/// <param name="postFix">文件后缀</param>/// <param name="saveDay">保存天数</param>private void DeleteFile(string fileDirect, string postFix, int saveDay){DateTime nowtime = DateTime.Now; //获取当前时间string[] files = Directory.GetFiles(fileDirect, postFix, SearchOption.AllDirectories); //获取该目录下所有 .txt文件foreach (string file in files){FileInfo fileInfo = new FileInfo(file);TimeSpan t = nowtime - fileInfo.CreationTime; //当前时间 减去 文件创建时间int day = t.Days;if (day > saveDay) //保存的时间 ; 单位:天{File.Delete(file); //删除超过时间的文件}}}
调用如下:
我把文件夹路径存到ini文件中,首先读出路径
同样把保存天数存到ini文件中(存的是控件ridiobutton的索引值,具体操作点击这里),然后读出索引值再使用switch来解析索引值对应的天数
最后调用删除文件的函数,这里删除的是excel表格,注意格式为" *.xls ",*不能省略
pathLast = @"\" + day + ".xls"; //文件名pathHeard = Ini.IniReadValue("配置文件", "path"); //文件夹path = pathHeard + pathLast; //文件路径string deleteDay = Ini.IniReadValue("清除文件", "day"); //定期删除文件天数int deleteDayValue = -1;switch (deleteDay){case "4":deleteDayValue = -1;break;case "3":deleteDayValue = 3;break;case "2":deleteDayValue = 7;break;case "1":deleteDayValue = 15;break;case "0":deleteDayValue = 30;break;default:break;}if (deleteDayValue >= 0){DeleteFile(pathHeard, "*.xls", deleteDayValue);}