C#删除指定目录下文件(保留指定几天前的日志文件)
/// <summary> /// 插入日志公用方法 /// </summary> /// <param name="msg"></param> public static void insertLogs(string msg) { //日志输出盘符物理路径 string pf = ConfigurationManager.AppSettings["PF"]; //判断文件路径是否存在,不存在则创建,记录日志 DateTime dt = DateTime.Now; DeleteLogs(pf); string filetxt = pf + dt.ToString("yyyy-MM-dd") + ".log"; if (!Directory.Exists(pf))//如果不存在就创建file文件夹 { Directory.CreateDirectory(@"" + pf + "");//创建某盘下该文件夹 } StreamWriter fs = new StreamWriter(filetxt, true, System.Text.Encoding.UTF8); msg = msg + "\r\n"; fs.Write(msg); fs.Flush(); fs.Close(); } //删除指定日期文件,保留7天 private static void DeleteLogs(string dir) { int days = 7; //日志保留时长 单位:天 string logsDay = ConfigurationManager.AppSettings["logsDay"]; if (!string.IsNullOrEmpty(logsDay)) { days = int.Parse(logsDay); } try { if (!Directory.Exists(dir)) { return; } var now = DateTime.Now; foreach (var f in Directory.GetFileSystemEntries(dir).Where(f => File.Exists(f))) { var t = File.GetCreationTime(f); var elapsedTicks = now.Ticks - t.Ticks; var elaspsedSpan = new TimeSpan(elapsedTicks); if (elaspsedSpan.TotalDays > days) { File.Delete(f); } } } catch (Exception ex) { } }