1
HuBingJie
5 天以前 99d55d437cc924429bb9589d5afe24f386cf8342
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
using Quartz;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using WIDESEA_Common.Log;
 
namespace WIDESEAWCS_Tasks
{
    [DisallowConcurrentExecution]
    public class LogJob : IJob
    {
        // 定义允许删除的根目录
        private static readonly string LogRootPath = Path.GetFullPath(Environment.CurrentDirectory + "/Log");
        private static readonly string PlatformInfoPath = Path.GetFullPath(Environment.CurrentDirectory + "/Log/站台读取信息记录");
 
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                Task.Run(() =>
                {
                    try
                    {
                            // 清理日志文件
                            CleanLogFilesOnly(LogRootPath, TimeSpan.FromMinutes(43200));
                            CleanAllInPlatformInfo(PlatformInfoPath, TimeSpan.FromMinutes(43200));
 
                            Thread.Sleep(1000 * 10); // 10秒后再次执行
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"日志任务执行异常: {ex.Message}");
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{nameof(LogJob)} 初始化异常: {ex.Message}");
            }
 
            return Task.CompletedTask;
        }
 
        /// <summary>
        /// 检查路径是否在允许删除的范围内
        /// </summary>
        /// <param name="path">要检查的路径</param>
        /// <param name="allowedRoot">允许的根目录</param>
        /// <returns>是否允许删除</returns>
        private static bool IsPathAllowed(string path, string allowedRoot)
        {
            try
            {
                var fullPath = Path.GetFullPath(path);
                return fullPath.StartsWith(allowedRoot, StringComparison.OrdinalIgnoreCase);
            }
            catch
            {
                return false;
            }
        }
 
        /// <summary>
        /// 只清理Log目录下的文件
        /// </summary>
        /// <param name="directoryPath">要清理的目录路径</param>
        /// <param name="maxAge">文件最大保留时间</param>
        private static void CleanLogFilesOnly(string directoryPath, TimeSpan maxAge)
        {
            if (!Directory.Exists(directoryPath))
            {
                //Console.WriteLine($"目录不存在: {directoryPath}");
                return;
            }
 
            try
            {
                var now = DateTime.Now;
                // 只获取当前目录的文件,不包含子目录
                var files = Directory.GetFiles(directoryPath, "*", SearchOption.TopDirectoryOnly);
                int deletedCount = 0;
 
                foreach (var file in files)
                {
                    try
                    {
                        // 检查文件是否在允许删除的范围内
                        if (!IsPathAllowed(file, LogRootPath))
                        {
                            Console.WriteLine($"跳过非Log目录文件: {file}");
                            continue;
                        }
 
                        // 获取文件创建时间
                        var creationTime = File.GetCreationTime(file);
 
                        // 检查文件是否超过指定时间
                        if (now - creationTime > maxAge)
                        {
                            File.Delete(file);
                            deletedCount++;
                            //Console.WriteLine($"已删除文件: {file}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"删除文件 {file} 时出错: {ex.Message}");
                    }
                }
 
                //Console.WriteLine($"目录 {directoryPath} 清理完成,删除了 {deletedCount} 个文件");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清理目录 {directoryPath} 时出错: {ex.Message}");
            }
        }
 
        /// <summary>
        /// 清理站台读取信息记录目录下的所有内容和子目录
        /// </summary>
        /// <param name="directoryPath">要清理的目录路径</param>
        /// <param name="maxAge">文件最大保留时间</param>
        private static void CleanAllInPlatformInfo(string directoryPath, TimeSpan maxAge)
        {
            if (!Directory.Exists(directoryPath))
            {
                //Console.WriteLine($"目录不存在: {directoryPath}");
                return;
            }
 
            try
            {
                var now = DateTime.Now;
                int deletedCount = 0;
 
                // 删除所有过期的文件
                var files = Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories);
                foreach (var file in files)
                {
                    try
                    {
                        // 检查文件是否在允许删除的范围内
                        if (!IsPathAllowed(file, PlatformInfoPath))
                        {
                            Console.WriteLine($"跳过非站台信息目录文件: {file}");
                            continue;
                        }
 
                        var creationTime = File.GetCreationTime(file);
                        if (now - creationTime > maxAge)
                        {
                            File.Delete(file);
                            deletedCount++;
                            //Console.WriteLine($"已删除文件: {file}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"删除文件 {file} 时出错: {ex.Message}");
                    }
                }
 
                // 删除所有空目录(包括子目录)
                DeleteAllEmptySubdirectories(directoryPath);
 
                //Console.WriteLine($"目录 {directoryPath} 清理完成,删除了 {deletedCount} 个文件");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清理目录 {directoryPath} 时出错: {ex.Message}");
            }
        }
 
        /// <summary>
        /// 递归删除所有空子目录
        /// </summary>
        /// <param name="directoryPath">要清理的目录路径</param>
        private static void DeleteAllEmptySubdirectories(string directoryPath)
        {
            if (!Directory.Exists(directoryPath))
                return;
 
            try
            {
                // 递归处理所有子目录
                foreach (var subDirectory in Directory.GetDirectories(directoryPath))
                {
                    // 检查目录是否在允许删除的范围内
                    if (!IsPathAllowed(subDirectory, PlatformInfoPath))
                    {
                        Console.WriteLine($"跳过非站台信息目录: {subDirectory}");
                        continue;
                    }
 
                    DeleteAllEmptySubdirectories(subDirectory);
 
                    // 检查子目录是否为空
                    var files = Directory.GetFiles(subDirectory);
                    var directories = Directory.GetDirectories(subDirectory);
 
                    if (files.Length == 0 && directories.Length == 0)
                    {
                        Directory.Delete(subDirectory);
                        //Console.WriteLine($"已删除空目录: {subDirectory}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理目录 {directoryPath} 时出错: {ex.Message}");
            }
        }
    }
}