【发布时间】:2015-08-25 12:06:00
【问题描述】:
我有一个保存日志文件的静态文件夹路径。我的问题是,我如何定期以编程方式删除它们,而不是手动删除。
我更喜欢 c# 代码。
【问题讨论】:
-
我们并不是真正的代码编写服务——到目前为止您尝试了哪些方法,您的方法发现了哪些问题?查看“How do I ask a good question?”获取一些提示。
我有一个保存日志文件的静态文件夹路径。我的问题是,我如何定期以编程方式删除它们,而不是手动删除。
我更喜欢 c# 代码。
【问题讨论】:
File.Delete(@"some_path_to_file");
编辑:如果你想遍历目录中的所有文件,你可以使用类似的东西
DirectoryInfo dir = new DirectoryInfo("your static folder path");
foreach (FileInfo f in dir.GetFiles())
{
File.Delete(f.FullName);
}
如果您需要“定期”执行此操作,您可以使用Quartz.NET 调度程序来调用此作业。它很容易设置。
【讨论】:
根据之前的答案,这是我想出的满足我需求的方法(大型 IIS 日志文件让我发疯!):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogFileDeleter
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo dir = new DirectoryInfo("c:\\inetpub\\logs\\logfiles\\w3svc1");
DateTime testDate = DateTime.Now.AddDays(-5);
foreach (FileInfo f in dir.GetFiles())
{
DateTime fileAge = f.LastWriteTime;
if (fileAge < testDate) {
Console.WriteLine("File " + f.Name + " is older than today, deleted...");
File.Delete(f.FullName);
}
//Console.ReadLine(); //Pause -- only needed in testing.
}
}
}
}
应该很明显,但它只删除超过 5 天的文件,并且只删除 W3SVC1 目录中的文件。
【讨论】:
try
{
if(File.Exists(filePath))
{
File.Delete(filePath);
}
}
catch{}
【讨论】: