C# Windows服务:自动删除日期文件夹及其文件

本文将介绍如何使用C#编写一个Windows服务,该服务可以自动删除指定文件夹下30天前的子文件夹及其文件。子文件夹名称以日期格式命名,例如'20230323'。

1. 创建服务项目

首先,创建一个名为'FolderCleaner'的Windows服务项目。

2. 配置文件夹路径

App.config文件中添加一个名为'FolderPaths'的AppSettings节点,用于存储要清理的文件夹路径。例如:

<appSettings>
  <add key="FolderPaths" value="C:\TestFolder1,C:\TestFolder2"/>
</appSettings>

3. 实现清理逻辑

在服务类中定义一个名为'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);
                }
            }
        }
    }
}

4. 定时执行

在服务类的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);
                        }
                    }
                }
            }
        }
    }
}

注意: 此代码仅为示例,可能需要进行一些修改和优化,以适应实际情况。

使用方法

  1. 将服务安装到系统中。
  2. 修改App.config文件中的FolderPaths节点,添加要清理的文件夹路径。
  3. 启动服务。

服务会按照配置的时间间隔自动清理指定文件夹下的日期文件夹。

总结

本文介绍了如何使用C#编写一个Windows服务,自动删除指定文件夹下30天前的子文件夹及其文件。该服务可以帮助您定期清理磁盘空间,并提高系统性能。

C# Windows服务:自动删除日期文件夹及其文件

原文地址: https://www.cveoy.top/t/topic/lPMy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录