以下是使用C#编写的遍历指定文件夹的Windows服务,可以配置多个文件夹,删除指定天数之前的子文件夹及其文件:

using System;
using System.IO;
using System.ServiceProcess;
using System.Configuration;

namespace DeleteOldFoldersService
{
    public partial class DeleteOldFolders : ServiceBase
    {
        private int daysToDelete;

        public DeleteOldFolders()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // 读取配置文件中指定的文件夹路径和天数
            string[] folderPaths = ConfigurationManager.AppSettings["FolderPaths"].Split(',');
            daysToDelete = int.Parse(ConfigurationManager.AppSettings["DaysToDelete"]);

            // 遍历每个文件夹并删除30天之前的子文件夹及其文件
            foreach (string folderPath in folderPaths)
            {
                DeleteOldFoldersInFolder(folderPath);
            }
        }

        protected override void OnStop()
        {
            // 停止服务时不做任何操作
        }

        private void DeleteOldFoldersInFolder(string folderPath)
        {
            DirectoryInfo folder = new DirectoryInfo(folderPath);
            if (!folder.Exists)
            {
                return;
            }

            foreach (DirectoryInfo subfolder in folder.GetDirectories())
            {
                // 子文件夹名称应为8位日期格式,否则跳过
                DateTime date;
                if (!DateTime.TryParseExact(subfolder.Name, 'yyyyMMdd', null, System.Globalization.DateTimeStyles.None, out date))
                {
                    continue;
                }

                // 判断子文件夹是否是30天之前的,是则删除
                if (DateTime.Now.Subtract(date).Days > daysToDelete)
                {
                    try
                    {
                        subfolder.Delete(true);
                    }
                    catch (Exception ex)
                    {
                        // 记录错误日志
                        EventLog.WriteEntry('DeleteOldFoldersService', 'Failed to delete folder ' + subfolder.FullName + ': ' + ex.Message, EventLogEntryType.Error);
                    }
                }
            }
        }
    }
}

需要在项目中添加对System.Configuration和System.ServiceProcess的引用。可以在项目属性的'设置'中添加两个配置项:FolderPaths和DaysToDelete,分别表示要遍历的文件夹路径和要删除的天数。例如:

FolderPaths: C:\TestFolder1,C:\TestFolder2
DaysToDelete: 30

这样,服务就可以遍历指定的文件夹,删除30天之前的子文件夹及其文件。如果有错误发生,将在Windows事件日志中记录。可以使用命令行工具sc.exe将服务安装到Windows服务中,例如:

sc.exe create DeleteOldFoldersService binPath= "C:\DeleteOldFoldersService.exe" start= auto

然后在Windows服务中启动服务即可。

C# Windows服务:自动删除指定文件夹下30天前的子文件夹和文件

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

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