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

前端 未结 18 2106
醉话见心
醉话见心 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 07:03

    since the solutions with new FileInfo(filePath) are not easily testable, I suggest to use Wrappers for classes like Directory, File and Path like this:

    public interface IDirectory
    {
        string[] GetFiles(string path);
    }
    
    public sealed class DirectoryWrapper : IDirectory
    {
        public string[] GetFiles(string path) => Directory.GetFiles(path);
    }
    
    public interface IFile
    {
        void Delete(string path);
        DateTime GetLastAccessTime(string path);
    }
    
    public sealed class FileWrapper : IFile
    {
        public void Delete(string path) => File.Delete(path);
        public DateTime GetLastAccessTimeUtc(string path) => File.GetLastAccessTimeUtc(path);
    }
    
    

    Then use something like this:

    public sealed class FooBar
    {
        public FooBar(IFile file, IDirectory directory)
        {
            File = file;
            Directory = directory;
        }
    
        private IFile File { get; }
        private IDirectory Directory { get; }
    
        public void DeleteFilesBeforeTimestamp(string path, DateTime timestamp)
        {
            if(!Directory.Exists(path))
                throw new DirectoryNotFoundException($"The path {path} was not found.");
    
            var files = Directory
                .GetFiles(path)
                .Select(p => new
                {
                    Path = p,
                    // or File.GetLastWriteTime() or File.GetCreationTime() as needed
                    LastAccessTimeUtc = File.GetLastAccessTimeUtc(p) 
                })
                .Where(p => p.LastAccessTimeUtc < timestamp);
    
            foreach(var file in files)
            {
                File.Delete(file.Path);
            }
        }
    }
    

提交回复
热议问题