Delete files older than 3 months old in a directory using .NET

前端 未结 18 2076
醉话见心
醉话见心 2020-12-02 06:31

I would like to know (using C#) how I can delete files in a certain directory older than 3 months, but I guess the date period could be flexible.

Just to be clear:

18条回答
  •  眼角桃花
    2020-12-02 06:47

    The most canonical approach when wanting to delete files over a certain duration is by using the file's LastWriteTime (Last time the file was modified):

    Directory.GetFiles(dirName)
             .Select(f => new FileInfo(f))
             .Where(f => f.LastWriteTime < DateTime.Now.AddMonths(-3))
             .ToList()
             .ForEach(f => f.Delete());
    

    (The above based on Uri's answer but with LastWriteTime.)

    Whenever you hear people talking about deleting files older than a certain time frame (which is a pretty common activity), doing it based on the file's LastModifiedTime is almost always what they are looking for.

    Alternatively, for very unusual circumstances you could use the below, but use these with caution as they come with caveats.

    CreationTime
    .Where(f => f.CreationTime < DateTime.Now.AddMonths(-3))
    

    The time the file was created in the current location. However, be careful if the file was copied, it will be the time it was copied and CreationTime will be newer than the file's LastWriteTime.

    LastAccessTime
    .Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
    

    If you want to delete the files based on the last time they were read you could use this but, there is no guarantee it will be updated as it can be disabled in NTFS. Check fsutil behavior query DisableLastAccess to see if it is on. Also under NTFS it may take up to an hour for the file's LastAccessTime to update after it was accessed.

提交回复
热议问题