1. 程式人生 > 實用技巧 >C# -linux下Log的自動刪除

C# -linux下Log的自動刪除

C# -linux下Log的自動刪除

對log的操作其實也就兩部分,找到log,判斷log生成時間是否超出規定時間,是則刪除,下面是程式碼實現,大家如果有相似問題,可以借鑑一下,也歡迎在品論區留下更好的解決方案。

public static void ClearLog()
        {             
            string logPath = AppDomain.CurrentDomain.BaseDirectory+ "Logs"; //獲取到更目錄下的logs資料夾          
            if (!Directory.Exists(logPath))
            {
                
return; } DirectoryInfo folder = new DirectoryInfo(logPath); FileSystemInfo[] files = folder.GetFileSystemInfos(); //獲取資料夾 if (files == null) { return; } foreach (FileSystemInfo file in files) {
string path_log_url = file.FullName; if (!Directory.Exists(path_log_url)) { continue; } DirectoryInfo folder_base = new DirectoryInfo(path_log_url); FileInfo[] files_base = folder_base.GetFiles("
*.txt"); //獲取.txt檔案 foreach (var file_txt in files_base) { //獲取檔案建立時間 DateTime fileCreateTime = file_txt.LastWriteTime; //獲取當前時間 DateTime now = DateTime.Now; int createMonth = fileCreateTime.Month; int nowMonth = now.Month; int distance = nowMonth - createMonth; distance = distance >= 0 ? distance : (distance + 12); 時間差 if (distance < 3) { //小於三個月不刪除 continue; } try { File.Delete(file_txt.FullName); } catch { throw new Exception("刪除日誌檔案出現異常"); } } }

在Linux上winds上測試都能完成Log的刪除。