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

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

    I use the following in a console app, running as a service, to get directory info from the App.Settings file. Number of days to keep the files is also configurable, multiplied by -1 for use in the AddDays() method of DateTime.Now.

    static void CleanBackupFiles()
            {
                string gstrUncFolder = ConfigurationManager.AppSettings["DropFolderUNC"] + "";
                int iDelAge = Convert.ToInt32(ConfigurationManager.AppSettings["NumDaysToKeepFiles"]) * -1;
                string backupdir = string.Concat(@"\", "Backup", @"\");
    
                string[] files = Directory.GetFiles(string.Concat(gstrUncFolder, backupdir));
    
    
                foreach (string file in files)
                {
                    FileInfo fi = new FileInfo(file);
                    if (fi.CreationTime < DateTime.Now.AddDays(iDelAge))
                    {
                        fi.Delete();
                    }
                }
    
            }
    

提交回复
热议问题