用C#写一个遍历指定文件夹,(子文件夹名称由日期组成,例如:2023年3月23日,就是20230323)删除30之前的子文件夹及其文件,的windwos服务,指定文件夹路径可使用配置文件配置,并可以配置多个文件夹
以下是一个可能的解决方案:
- 创建一个名为"FolderCleaner"的Windows服务项目。
- 在App.config文件中添加一个名为"FolderPaths"的AppSettings节点,用于存储要清理的文件夹路径。例如:
<appSettings>
<add key="FolderPaths" value="C:\TestFolder1,C:\TestFolder2"/>
</appSettings>
- 在服务类中定义一个名为"CleanFolders"的方法,用于遍历指定的文件夹并删除早于30天的子文件夹及其文件。可以使用System.IO.Directory类的方法来实现这个方法。例如:
private void CleanFolders()
{
string[] folderPaths = ConfigurationManager.AppSettings["FolderPaths"].Split(',');
foreach (string folderPath in folderPaths)
{
foreach (string subFolderPath in Directory.GetDirectories(folderPath))
{
string subFolderName = Path.GetFileName(subFolderPath);
if (subFolderName.Length == 8 && DateTime.TryParseExact(subFolderName, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime subFolderDate))
{
if (subFolderDate < DateTime.Today.AddDays(-30))
{
Directory.Delete(subFolderPath, true);
}
}
}
}
}
- 在服务类的OnStart方法中添加一个定时器,每隔一定时间调用CleanFolders方法。例如:
protected override void OnStart(string[] args)
{
_timer = new Timer();
_timer.Interval = TimeSpan.FromMinutes(30).TotalMilliseconds; //每30分钟执行一次
_timer.Elapsed += (sender, eventArgs) => CleanFolders();
_timer.AutoReset = true;
_timer.Start();
}
完整代码如下所示:
using System;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.ServiceProcess;
using System.Timers;
namespace FolderCleaner
{
public partial class FolderCleanerService : ServiceBase
{
private Timer _timer;
public FolderCleanerService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_timer = new Timer();
_timer.Interval = TimeSpan.FromMinutes(30).TotalMilliseconds; //每30分钟执行一次
_timer.Elapsed += (sender, eventArgs) => CleanFolders();
_timer.AutoReset = true;
_timer.Start();
}
protected override void OnStop()
{
_timer.Stop();
_timer.Dispose();
}
private void CleanFolders()
{
string[] folderPaths = ConfigurationManager.AppSettings["FolderPaths"].Split(',');
foreach (string folderPath in folderPaths)
{
foreach (string subFolderPath in Directory.GetDirectories(folderPath))
{
string subFolderName = Path.GetFileName(subFolderPath);
if (subFolderName.Length == 8 && DateTime.TryParseExact(subFolderName, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime subFolderDate))
{
if (subFolderDate < DateTime.Today.AddDays(-30))
{
Directory.Delete(subFolderPath, true);
}
}
}
}
}
}
}
请注意,此代码仅为示例,可能需要进行一些修改和优化,以适应实际情况。
原文地址: https://www.cveoy.top/t/topic/Bqx 著作权归作者所有。请勿转载和采集!