using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace JinYuan.Helper { public class DeleteLog { public static void Start(string strPata) { Init(strPata); } private static void Init(string strPata) { Task.Run(() => { try { while (true) { bool b = DeleteFile(strPata, 30); //删除该目录下 超过 30天的文件 if (b) LoggerHelp.WriteLog("已清除30天内过期日志"); //24小时清一次 Thread.Sleep(1000 * 60 * 60 * 24); } } catch (Exception e) { Thread.Sleep(1000 * 60 * 60 * 28); } }); } public static void DeleteDirectory(string target_dir) { string[] files = Directory.GetFiles(target_dir); string[] dirs = Directory.GetDirectories(target_dir); foreach (string file in files) { File.SetAttributes(file, FileAttributes.Normal); File.Delete(file); } foreach (string dir in dirs) { DeleteDirectory(dir); } Directory.Delete(target_dir, false); } private static bool DeleteFile(string fileDirect, int saveDay) { try { DateTime nowTime = DateTime.Now; string[] files = Directory.GetFiles(fileDirect, "*.*", SearchOption.AllDirectories); //获取该目录下所有 .txt文件 foreach (string file in files) { FileInfo fileInfo = new FileInfo(file); TimeSpan t = DateTime.Now - fileInfo.CreationTime; //当前时间 减去 文件创建时间 int day = t.Days; if (day > saveDay) //保存的时间,单位:天 { if (IsOccupy(fileInfo.FullName)) //判断文件是否被占用 { System.IO.File.Delete(fileInfo.FullName); //删除文件 Directory.Delete(fileDirect, true); return true; } else { LoggerHelp.WriteLog("文件被占用,无法操作!"); } } } } catch (Exception err) { LoggerHelp.WriteLog($"文件被占用,无法操作!{err}"); } return false; } [DllImport("kernel32.dll")] public static extern IntPtr _lopen(string lpPathName, int iReadWrite); [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr hObject); public const int OF_READWRITE = 2; public const int OF_SHARE_DENY_NONE = 0x40; public static readonly IntPtr HFILE_ERROR = new IntPtr(-1); /// /// 判断文件是否被占用 /// /// /// private static bool IsOccupy(string file) { bool result = true; //默认状态此文件未被占用 try { //string vFileName = @"c:\temp\temp.bmp"; string vFileName = file; if (!System.IO.File.Exists(vFileName)) { //Logger.Info("文件都不存在!"); result = false; } IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE); if (vHandle == HFILE_ERROR) { //Log4Helper.WriteLog("文件被占用!", "错误提示"); result = false; } CloseHandle(vHandle); // Log4Helper.WriteLog("没有被占用!", "错误提示"); } catch (Exception err) { result = false; //Log4Helper.WriteLog("判断文件是否被占用", err); } return result; } } }