C# 刪除(delete),建立日期超過7天的資料(檔案)
C# 刪除(delete),建立日期超過7天的資料(檔案)
資料來源: https://ithelp.ithome.com.tw/questions/10198965
code
using System;
using System.IO;
using System.Linq;
namespace delOld
{
class Program
{
static void Main(string[] args)
{
DateTime now = DateTime.Now; // 今天
DirectoryInfo di = new DirectoryInfo(@"X:\"); // 取得 X:\ 資料夾資訊
// 從 di 裡找出所有zip檔,且列舉出所有 (今天 - 屬性日期) 超過 N 天的
//建立日期:p.CreationTime
//修改日期:p.LastWriteTime [個人喜歡用這個,方便測試]
//存取日期:p.LastAccessTime
// 用 foreach把上行列舉到的檔案全跑一遍,z 就是每次被列舉到符合條件的zip
foreach (var z in di.GetFiles("*.zip").Where(p => (now - p.CreationTime).TotalDays > 7))
{
z.Delete(); // 很好理解,把 z 刪除!
Console.WriteLine($"{z.FullName}: 已刪除");
// 因為我是用類似DOS視窗的Console模式寫這種程式,所以標準顯示目標就是Console啦
}
Console.WriteLine("刪除完畢,按任一鍵結束");
Console.ReadKey(); // 跟批次檔裡的PAUSE同義
}
}
}