使用C#创建Windows服务:自动清理指定文件夹中超过30天的子文件夹

本文将介绍如何使用C#创建一个Windows服务,自动清理指定文件夹中超过30天的子文件夹及其文件。该服务支持配置多个文件夹路径和清理天数,并每天运行一次。

步骤:

  1. 创建Windows服务项目:

    • 打开Visual Studio,选择新建项目,选择'Windows服务'项目类型,取一个合适的名字,例如'FolderCleanupService'。
  2. 添加配置文件:

    • 在项目中添加一个配置文件,用于存储需要清理的文件夹路径和清理天数。
    • 右键项目,选择'添加' -> '新建项',选择'应用程序配置文件',命名为'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天。
  3. 创建清理服务类:

    • 在服务项目中添加一个类,命名为'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位日期格式,并且小于清理日期,则删除该子文件夹及其文件。
  4. 配置服务启动:

    • 在'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);
            }
        }
    }
    
  5. 编译、发布和安装服务:

    • 在Visual Studio中,右键项目,选择'发布' -> '创建发布目标',选择'文件夹',指定发布路径,生成发布文件。
    • 以管理员身份打开命令提示符,切换到发布文件所在目录,执行以下命令安装服务:
    FolderCleanupService.exe install
    
    • 安装成功后,可以在Windows服务中找到该服务,并启动它。

至此,一个遍历指定文件夹,删除30天之前的子文件夹及其文件的Windows服务就完成了。


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

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