Ad Code

Responsive Advertisement

Console App Task 05: How to delete files older than 3 months in C#

Console App Task 05: How to delete files older than 3 months in C# 

If you want to delete files older than 3 months, you can modify the previous code like this:


C# Code: Delete Files Older Than 3 Months

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string folderPath = @"C:\Your\Target\Directory"; // Change this to your target folder
        DateTime threeMonthsAgo = DateTime.Now.AddMonths(-3);

        try
        {
            // Get all files in the folder
            string[] files = Directory.GetFiles(folderPath);

            foreach (string file in files)
            {
                // Get file creation time
                DateTime fileCreationTime = File.GetCreationTime(file);

                // Check if the file is older than 3 months
                if (fileCreationTime < threeMonthsAgo)
                {
                    Console.WriteLine($"Deleting file: {file}");
                    File.Delete(file);
                }
            }

            Console.WriteLine("File cleanup completed.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

📝 How It Works

  1. Gets all files in the target directory.
  2. Checks each file's creation date.
  3. Deletes files older than 3 months.

If you like comment and share. 🚀

Post a Comment

0 Comments

Ad Code

Responsive Advertisement