Ad Code

Responsive Advertisement

Console App Task 04: How to delete folders older than 3 months in C#

Console App Task 04: How to delete folders older than 3 months in C# 

You can use the following C# code to delete folders older than 3 months from a specified directory:

Code: Delete Folders Older Than 3 Months

using System;
using System.IO;

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

        try
        {
            // Get all directories in the specified folder
            string[] folders = Directory.GetDirectories(folderPath);

            foreach (string folder in folders)
            {
                // Get folder creation time
                DateTime folderCreationTime = Directory.GetCreationTime(folder);

                // Check if the folder is older than 3 months
                if (folderCreationTime < threeMonthsAgo)
                {
                    Console.WriteLine($"Deleting folder: {folder}");
                    Directory.Delete(folder, true); // true allows recursive delete
                }
            }

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

📝 How It Works:

  1. Gets all folders in the specified directory.
  2. Checks each folder’s creation date.
  3. Deletes folders older than 3 months.

Make sure to run this code carefully as it will permanently delete folders.

If you like comment and share. 🚀

Post a Comment

0 Comments

Ad Code

Responsive Advertisement