---
title: "Compress old log files (e.g., ZIP after 7 days)?"  
description: "Compress old log files (e.g., ZIP after 7 days)?"  
author: "ICSM Computer"  
published: 2025-05-29  
updated: 2025-05-29  
canonical: https://www.mindstick.com/interview/34182/compress-old-log-files-e-g-zip-after-7-days  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 3 minutes  

---

# Compress old log files (e.g., ZIP after 7 days)?

Great idea. Compressing old logs after 7 days reduces disk usage and keeps your app clean.

Here’s a step-by-step plan to **automatically compress log files older than 7 days** into `.zip` files and optionally delete the originals.

## Step 1: Add NuGet Reference (if needed)

If you're not already referencing `System.IO.Compression.FileSystem`, install it via NuGet:

```plaintext
Install-Package System.IO.Compression.FileSystem
```

## Step 2: Compression Helper (ZIP Old Logs)

```cs
using System.IO.Compression;

public static class LogCompressor
{
    public static void CompressOldLogs(string logDirectory, int olderThanDays = 7)
    {
        if (!Directory.Exists(logDirectory))
            return;

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

        foreach (var logFile in logFiles)
        {
            try
            {
                string fileName = Path.GetFileNameWithoutExtension(logFile); // e.g., UserActivityLog_2025-05-20
                string zipFile = Path.Combine(logDirectory, fileName + ".zip");

                using (FileStream zipToOpen = new FileStream(zipFile, FileMode.Create))
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    archive.CreateEntryFromFile(logFile, Path.GetFileName(logFile));
                }

                File.Delete(logFile); // delete the original
            }
            catch
            {
                // handle or log exception, don't break app
            }
        }
    }
}
```

## Step 3: Call It Periodically (e.g., Global.asax or Scheduler)

In `Global.asax.cs`:

```cs
protected void Application_Start()
{
    // Other setup...

    Task.Run(() =>
    {
        string logDir = HttpContext.Current.Server.MapPath("~/App_Data/UserLogs");
        LogCompressor.CompressOldLogs(logDir);
    });
}
```

**Or** schedule it using a background task or external job if your app runs long-term.

## Result

1. `UserActivityLog_2025-05-20.txt` → `UserActivityLog_2025-05-20.zip`
2. Original `.txt` is deleted (can be optional)
3. Remaining logs under 7 days are untouched

### Optional Enhancements:

1. Keep both ZIP and TXT?
2. Email compressed logs?
3. Archive logs to a separate folder like `~/App_Data/LogArchive`?

## Answers

### Answer by ICSM Computer

Great idea. Compressing old logs after 7 days reduces disk usage and keeps your app clean.

Here’s a step-by-step plan to **automatically compress log files older than 7 days** into `.zip` files and optionally delete the originals.

## Step 1: Add NuGet Reference (if needed)

If you're not already referencing `System.IO.Compression.FileSystem`, install it via NuGet:

```plaintext
Install-Package System.IO.Compression.FileSystem
```

## Step 2: Compression Helper (ZIP Old Logs)

```cs
using System.IO.Compression;

public static class LogCompressor
{
    public static void CompressOldLogs(string logDirectory, int olderThanDays = 7)
    {
        if (!Directory.Exists(logDirectory))
            return;

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

        foreach (var logFile in logFiles)
        {
            try
            {
                string fileName = Path.GetFileNameWithoutExtension(logFile); // e.g., UserActivityLog_2025-05-20
                string zipFile = Path.Combine(logDirectory, fileName + ".zip");

                using (FileStream zipToOpen = new FileStream(zipFile, FileMode.Create))
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    archive.CreateEntryFromFile(logFile, Path.GetFileName(logFile));
                }

                File.Delete(logFile); // delete the original
            }
            catch
            {
                // handle or log exception, don't break app
            }
        }
    }
}
```

## Step 3: Call It Periodically (e.g., Global.asax or Scheduler)

In `Global.asax.cs`:

```cs
protected void Application_Start()
{
    // Other setup...

    Task.Run(() =>
    {
        string logDir = HttpContext.Current.Server.MapPath("~/App_Data/UserLogs");
        LogCompressor.CompressOldLogs(logDir);
    });
}
```

**Or** schedule it using a background task or external job if your app runs long-term.

## Result

1. `UserActivityLog_2025-05-20.txt` → `UserActivityLog_2025-05-20.zip`
2. Original `.txt` is deleted (can be optional)
3. Remaining logs under 7 days are untouched

### Optional Enhancements:

1. Keep both ZIP and TXT?
2. Email compressed logs?
3. Archive logs to a separate folder like `~/App_Data/LogArchive`?


---

Original Source: https://www.mindstick.com/interview/34182/compress-old-log-files-e-g-zip-after-7-days

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
