Files

138 lines
4.4 KiB
C#
Raw Permalink Normal View History

2025-07-16 18:08:40 +08:00
using System;
using System.IO;
using System.Runtime.InteropServices;
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)
2025-07-31 10:01:09 +08:00
LoggerHelp.WriteLog("已清除30天内过期日志");
2025-07-16 18:08:40 +08:00
//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
{
2025-07-31 10:01:09 +08:00
LoggerHelp.WriteLog("文件被占用,无法操作!");
2025-07-16 18:08:40 +08:00
}
}
}
}
catch (Exception err)
{
2025-07-31 10:01:09 +08:00
LoggerHelp.WriteLog($"文件被占用,无法操作!{err}");
2025-07-16 18:08:40 +08:00
}
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);
/// <summary>
/// 判断文件是否被占用
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
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;
}
}
}