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

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

    The GetLastAccessTime property on the System.IO.File class should help.

    0 讨论(0)
  • Just create a small delete function which can help you to achieve this task, I have tested this code and it runs perfectly well.

    This function deletes files older than 90 days as well as a file with extension .zip to be deleted from a folder.

    Private Sub DeleteZip()
    
        Dim eachFileInMydirectory As New DirectoryInfo("D:\Test\")
        Dim fileName As IO.FileInfo
    
        Try
            For Each fileName In eachFileInMydirectory.GetFiles
                If fileName.Extension.Equals("*.zip") AndAlso (Now - fileName.CreationTime).Days > 90 Then
                    fileName.Delete()
                End If
            Next
    
        Catch ex As Exception
            WriteToLogFile("No Files older than 90 days exists be deleted " & ex.Message)
        End Try
    End Sub
    
    0 讨论(0)
  • 2020-12-02 07:06

    For those that like to over-use LINQ.

    (from f in new DirectoryInfo("C:/Temp").GetFiles()
     where f.CreationTime < DateTime.Now.Subtract(TimeSpan.FromDays(90))
     select f
    ).ToList()
        .ForEach(f => f.Delete());
    
    0 讨论(0)
  • 2020-12-02 07:07

    An SSIS type of example .. (if this helps anyone)

              public void Main()
              {
                     // TODO: Add your code here
            // Author: Allan F 10th May 2019
    
            //first part of process .. put any files of last Qtr (or older) in Archive area 
            //e.g. if today is 10May2019 then last quarter is 1Jan2019 to 31March2019 .. any files earlier than 31March2019 will be archived
    
            //string SourceFileFolder = "\\\\adlsaasf11\\users$\\aford05\\Downloads\\stage\\";
            string SourceFilesFolder = (string)Dts.Variables["SourceFilesFolder"].Value;
            string ArchiveFolder = (string)Dts.Variables["ArchiveFolder"].Value;
            string FilePattern = (string)Dts.Variables["FilePattern"].Value;
            string[] files = Directory.GetFiles(SourceFilesFolder, FilePattern);
    
            //DateTime date = new DateTime(2019, 2, 15);//commented out line .. just for testing the dates .. 
    
            DateTime date = DateTime.Now;
            int quarterNumber = (date.Month - 1) / 3 + 1;
            DateTime firstDayOfQuarter = new DateTime(date.Year, (quarterNumber - 1) * 3 + 1, 1);
            DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);
    
            DateTime LastDayOfPriorQuarter = firstDayOfQuarter.AddDays(-1);
            int PrevQuarterNumber = (LastDayOfPriorQuarter.Month - 1) / 3 + 1;
            DateTime firstDayOfLastQuarter = new DateTime(LastDayOfPriorQuarter.Year, (PrevQuarterNumber - 1) * 3 + 1, 1);
            DateTime lastDayOfLastQuarter = firstDayOfLastQuarter.AddMonths(3).AddDays(-1);
    
            //MessageBox.Show("debug pt2: firstDayOfQuarter" + firstDayOfQuarter.ToString("dd/MM/yyyy"));
            //MessageBox.Show("debug pt2: firstDayOfLastQuarter" + firstDayOfLastQuarter.ToString("dd/MM/yyyy"));
    
    
            foreach (string file in files)
            {
                FileInfo fi = new FileInfo(file);
    
                //MessageBox.Show("debug pt2:" + fi.Name + " " + fi.CreationTime.ToString("dd/MM/yyyy HH:mm") + " " + fi.LastAccessTime.ToString("dd/MM/yyyy HH:mm") + " " + fi.LastWriteTime.ToString("dd/MM/yyyy HH:mm"));
                if (fi.LastWriteTime < firstDayOfQuarter)
                {
    
                    try
                    {
    
                        FileInfo fi2 = new FileInfo(ArchiveFolder);
    
                        //Ensure that the target does not exist.
                        //fi2.Delete();
    
                        //Copy the file.
                        fi.CopyTo(ArchiveFolder + fi.Name);
                        //Console.WriteLine("{0} was copied to {1}.", path, ArchiveFolder);
    
                        //Delete the old location file.
                        fi.Delete();
                        //Console.WriteLine("{0} was successfully deleted.", ArchiveFolder);
    
                    }
                    catch (Exception e)
                    {
                        //do nothing
                        //Console.WriteLine("The process failed: {0}", e.ToString());
                    }
                }
            }
    
            //second part of process .. delete any files in Archive area dated earlier than last qtr ..
            //e.g. if today is 10May2019 then last quarter is 1Jan2019 to 31March2019 .. any files earlier than 1Jan2019 will be deleted
    
            string[] archivefiles = Directory.GetFiles(ArchiveFolder, FilePattern);
            foreach (string archivefile in archivefiles)
            {
                FileInfo fi = new FileInfo(archivefile);
                if (fi.LastWriteTime < firstDayOfLastQuarter )
                {
                    try
                    {
                        fi.Delete();
                    }
                    catch (Exception e)
                    {
                        //do nothing
                    }
                }
            }
    
    
                     Dts.TaskResult = (int)ScriptResults.Success;
              }
    
    0 讨论(0)
  • 2020-12-02 07:08

    Here's a snippet of how to get the creation time of files in the directory and find those which have been created 3 months ago (90 days ago to be exact):

        DirectoryInfo source = new DirectoryInfo(sourceDirectoryPath);
    
        // Get info of each file into the directory
        foreach (FileInfo fi in source.GetFiles())
        {
            var creationTime = fi.CreationTime;
    
            if(creationTime < (DateTime.Now- new TimeSpan(90, 0, 0, 0)))
            {
                fi.Delete();
            }
        }
    
    0 讨论(0)
  • 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();
                    }
                }
    
            }
    
    0 讨论(0)
提交回复
热议问题