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:
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);
}
}
}