---
title: "Automatically delete logs older than X days?"  
description: "Automatically delete logs older than X days?"  
author: "ICSM Computer"  
published: 2025-05-29  
updated: 2025-05-29  
canonical: https://www.mindstick.com/interview/34183/automatically-delete-logs-older-than-x-days  
category: "c#"  
tags: ["c#"]  
reading_time: 2 minutes  

---

# Automatically delete logs older than X days?

Absolutely — you can **automatically delete log files older than a specified number of days** (e.g., 30 days) to keep your disk clean and avoid storage bloat.

Here’s a clean implementation.

## Step-by-Step: Auto-Delete Old Log Files

### `LogCleaner` Utility

```cs
public static class LogCleaner
{
    public static void DeleteOldLogs(string logDirectory, int olderThanDays = 30)
    {
        if (!Directory.Exists(logDirectory))
            return;

        var files = Directory.GetFiles(logDirectory, "*.*", SearchOption.TopDirectoryOnly)
            .Where(file => File.GetCreationTimeUtc(file) < DateTime.UtcNow.AddDays(-olderThanDays));

        foreach (var file in files)
        {
            try
            {
                File.Delete(file);
            }
            catch
            {
                // Optional: Log this failure to a fallback logger
            }
        }
    }
}
```

## Example Usage

You can call this cleanup together with your ZIP logic or as a standalone scheduled task.

### Example: Run on App Start (`Global.asax.cs`)

```cs
protected void Application_Start()
{
    Task.Run(() =>
    {
        string logDir = HttpContext.Current.Server.MapPath("~/App_Data/UserLogs");

        LogCompressor.CompressOldLogs(logDir, 7);     // compress logs older than 7 days
        LogCleaner.DeleteOldLogs(logDir, 30);         // delete logs older than 30 days
    });
}
```

## Optional Enhancements

Would you like to:

1. Move logs to an `Archive` folder instead of deleting?
2. Email a report of deleted/compressed logs?
3. Only delete `.txt`, not `.zip`?

## Answers

### Answer by ICSM Computer

Absolutely — you can **automatically delete log files older than a specified number of days** (e.g., 30 days) to keep your disk clean and avoid storage bloat.

Here’s a clean implementation.

## Step-by-Step: Auto-Delete Old Log Files

### `LogCleaner` Utility

```cs
public static class LogCleaner
{
    public static void DeleteOldLogs(string logDirectory, int olderThanDays = 30)
    {
        if (!Directory.Exists(logDirectory))
            return;

        var files = Directory.GetFiles(logDirectory, "*.*", SearchOption.TopDirectoryOnly)
            .Where(file => File.GetCreationTimeUtc(file) < DateTime.UtcNow.AddDays(-olderThanDays));

        foreach (var file in files)
        {
            try
            {
                File.Delete(file);
            }
            catch
            {
                // Optional: Log this failure to a fallback logger
            }
        }
    }
}
```

## Example Usage

You can call this cleanup together with your ZIP logic or as a standalone scheduled task.

### Example: Run on App Start (`Global.asax.cs`)

```cs
protected void Application_Start()
{
    Task.Run(() =>
    {
        string logDir = HttpContext.Current.Server.MapPath("~/App_Data/UserLogs");

        LogCompressor.CompressOldLogs(logDir, 7);     // compress logs older than 7 days
        LogCleaner.DeleteOldLogs(logDir, 30);         // delete logs older than 30 days
    });
}
```

## Optional Enhancements

Would you like to:

1. Move logs to an `Archive` folder instead of deleting?
2. Email a report of deleted/compressed logs?
3. Only delete `.txt`, not `.zip`?


---

Original Source: https://www.mindstick.com/interview/34183/automatically-delete-logs-older-than-x-days

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
