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

前端 未结 18 1992
醉话见心
醉话见心 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:55

    i have try this code and it works very well, hope this answered

    namespace EraseJunkFiles
    {
        class Program
        {
            static void Main(string[] args)
            {
                DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\yourdirectory\");
                foreach (FileInfo file in yourRootDir.GetFiles())
                    if (file.LastWriteTime < DateTime.Now.AddDays(-90))
                        file.Delete();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-02 06:56

    you just need FileInfo -> CreationTime

    and than just calculate the time difference.

    in the app.config you can save the TimeSpan value of how old the file must be to be deleted

    also check out the DateTime Subtract method.

    good luck

    0 讨论(0)
  • 2020-12-02 06:57

    Alternatively, you can use the File.GetCreationTime Method if you need to delete files based on creation dates.

    0 讨论(0)
  • 2020-12-02 06:58

    For example: To go My folder project on source, i need to up two folder. I make this algorim to 2 days week and into four hour

    public static void LimpiarArchivosViejos()
        {
            DayOfWeek today = DateTime.Today.DayOfWeek;
            int hora = DateTime.Now.Hour;
            if(today == DayOfWeek.Monday || today == DayOfWeek.Tuesday && hora < 12 && hora > 8)
            {
                CleanPdfOlds();
                CleanExcelsOlds();
            }
    
        }
        private static void CleanPdfOlds(){
            string[] files = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Reports");
            foreach (string file in files)
            {
                FileInfo fi = new FileInfo(file);
                if (fi.CreationTime < DateTime.Now.AddDays(-7))
                    fi.Delete();
            }
        }
        private static void CleanExcelsOlds()
        {
            string[] files2 = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Excels");
            foreach (string file in files2)
            {
                FileInfo fi = new FileInfo(file);
                if (fi.CreationTime < DateTime.Now.AddDays(-7))
                    fi.Delete();
            }
        }
    
    0 讨论(0)
  • 2020-12-02 07:01
                system.IO;
    
                 List<string> DeletePath = new List<string>();
                DirectoryInfo info = new DirectoryInfo(Server.MapPath("~\\TempVideos"));
                FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
                foreach (FileInfo file in files)
                {
                    DateTime CreationTime = file.CreationTime;
                    double days = (DateTime.Now - CreationTime).TotalDays;
                    if (days > 7)
                    {
                        string delFullPath = file.DirectoryName + "\\" + file.Name;
                        DeletePath.Add(delFullPath);
                    }
                }
                foreach (var f in DeletePath)
                {
                    if (File.Exists(F))
                    {
                        File.Delete(F);
                    }
                }
    

    use in page load or webservice or any other use.

    My concept is evrry 7 day i have to delete folder file without using DB

    0 讨论(0)
  • 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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题