C# 定时清除日志文件
以下是一个C#程序,用于定时清除指定目录下的日志文件:
using System;
using System.IO;
using System.Threading;
class Program
{
static void Main()
{
// 设置日志目录
string logDirectory = "C:\\Logs";
// 设置清除日志的时间间隔(单位:天)
int interval = 7;
while (true)
{
// 获取当前时间
DateTime currentTime = DateTime.Now;
// 获取待清除的时间
DateTime deleteTime = currentTime.AddDays(-interval);
// 获取所有日志文件
string[] logFiles = Directory.GetFiles(logDirectory, "*.log");
foreach (string logFile in logFiles)
{
// 获取文件的创建时间
DateTime fileCreationTime = File.GetCreationTime(logFile);
// 如果文件的创建时间早于待清除的时间,则删除该文件
if (fileCreationTime < deleteTime)
{
File.Delete(logFile);
}
}
// 等待一天
Thread.Sleep(TimeSpan.FromDays(1));
}
}
}
上述程序会每天循环一次,检查指定目录下的所有日志文件的创建时间。如果某个日志文件的创建时间早于指定的时间间隔,则删除该文件
原文地址: https://www.cveoy.top/t/topic/iZRj 著作权归作者所有。请勿转载和采集!