用C#写一个遍历指定文件夹,(子文件夹名称由日期组成,例如:2023年3月23日,就是20230323)删除30天之前的子文件夹及其文件(天数可配置),的windwos服务,指定文件夹路径可使用配置文件配置,并可以配置多个文件夹,每天运行一次
首先,需要创建一个Windows服务项目。具体步骤如下:
-
打开Visual Studio,选择新建项目,选择“Windows服务”项目类型,取一个合适的名字,例如“FolderCleanupService”。
-
在项目中添加一个配置文件,用于存储需要清理的文件夹路径和清理天数。右键项目,选择“添加” -> “新建项”,选择“应用程序配置文件”,命名为“app.config”。
-
在配置文件中,添加以下内容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="FolderPaths" value="C:\Folder1,C:\Folder2" />
<add key="CleanupDays" value="30" />
</appSettings>
</configuration>
其中,FolderPaths为需要清理的文件夹路径,多个路径用逗号分隔;CleanupDays为清理的天数,默认为30天。
-
在服务项目中添加一个类,命名为“FolderCleanupService”,继承自“ServiceBase”类。
-
在类中添加以下代码:
using System;
using System.IO;
using System.ServiceProcess;
using System.Configuration;
namespace FolderCleanupService
{
public partial class FolderCleanupService : ServiceBase
{
private string[] folderPaths;
private int cleanupDays;
public FolderCleanupService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//读取配置文件中的FolderPaths和CleanupDays
folderPaths = ConfigurationManager.AppSettings["FolderPaths"].Split(',');
cleanupDays = int.Parse(ConfigurationManager.AppSettings["CleanupDays"]);
//启动定时器,每天执行一次清理任务
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoCleanup);
timer.Interval = 24 * 60 * 60 * 1000; //24小时执行一次
timer.Start();
}
protected override void OnStop()
{
}
private void DoCleanup(object sender, System.Timers.ElapsedEventArgs e)
{
foreach (string folderPath in folderPaths)
{
try
{
//获取当前日期减去清理天数之后的日期
DateTime cleanupDate = DateTime.Now.AddDays(-cleanupDays);
//遍历子文件夹,删除30天之前的文件夹及其文件
DirectoryInfo root = new DirectoryInfo(folderPath);
foreach (DirectoryInfo subFolder in root.GetDirectories())
{
if (subFolder.Name.Length == 8) //子文件夹名称必须为8位日期格式
{
DateTime subFolderDate;
if (DateTime.TryParseExact(subFolder.Name, "yyyyMMdd", null, System.Globalization.DateTimeStyles.None, out subFolderDate))
{
if (subFolderDate < cleanupDate)
{
subFolder.Delete(true); //删除子文件夹及其文件
}
}
}
}
}
catch (Exception ex)
{
//记录日志
}
}
}
}
}
在DoCleanup方法中,首先获取当前日期减去清理天数之后的日期,然后遍历子文件夹,如果子文件夹名称为8位日期格式,并且小于清理日期,则删除该子文件夹及其文件。
- 在“Program.cs”文件中,添加以下代码:
using System;
using System.ServiceProcess;
namespace FolderCleanupService
{
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new FolderCleanupService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
- 编译并安装Windows服务。在Visual Studio中,右键项目,选择“发布” -> “创建发布目标”,选择“文件夹”,指定发布路径,生成发布文件。然后以管理员身份打开命令提示符,切换到发布文件所在目录,执行以下命令安装服务:
FolderCleanupService.exe install
安装成功后,可以在Windows服务中找到该服务,并启动它。
至此,一个遍历指定文件夹,删除30天之前的子文件夹及其文件的Windows服务就完成了。
原文地址: https://www.cveoy.top/t/topic/BqO 著作权归作者所有。请勿转载和采集!