首页 > 其他分享 >删除5天前旧日志 以防日志占用大量硬盘空间

删除5天前旧日志 以防日志占用大量硬盘空间

时间:2022-11-26 15:31:17浏览次数:42  
标签:删除 DirectoryInfo 天前 logDir 日志 TheFolder 硬盘空间

/// <summary>
/// 删除5天前旧日志 以防日志占用大量硬盘空间
/// </summary>
public static void DelOverdueFiles(int days = 5)
{
string logDir = AppDomain.CurrentDomain.BaseDirectory + "/logs/";
if (!Directory.Exists(logDir)) return;
DirectoryInfo TheFolder = new DirectoryInfo(logDir);
var files = TheFolder.GetFiles("*", SearchOption.AllDirectories);
//删除5天前 所有文件
foreach (FileInfo f in files.Where(f => (DateTime.Now - f.CreationTime).TotalDays > days))
{
try
{
File.Delete(f.FullName);
}
catch (Exception e) { }
}
var dirs = TheFolder.GetDirectories("*", SearchOption.AllDirectories);
//删除空文件夹
foreach (DirectoryInfo d in dirs)
{
try
{
if (d.GetFiles().Length == 0)
{
Directory.Delete(d.FullName);
}
}
catch (Exception e) { }
}
}

 



标签:删除,DirectoryInfo,天前,logDir,日志,TheFolder,硬盘空间
From: https://blog.51cto.com/simadi/5888957

相关文章