---
title: "How can you restrict file size when writing to a log file?"  
description: "How can you restrict file size when writing to a log file?"  
author: "ICSM Computer"  
published: 2025-05-12  
updated: 2025-05-12  
canonical: https://www.mindstick.com/interview/34108/how-can-you-restrict-file-size-when-writing-to-a-log-file  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 3 minutes  

---

# How can you restrict file size when writing to a log file?

To **restrict the size of a log file** in C#, you typically check the file size **before writing**, and take action if it exceeds a limit — like **rotating**, **truncating**, or **archiving** the file.

### Example: Limit log file to 5 MB

```cs
using System;
using System.IO;

class Program
{
    static readonly string logPath = @"C:\Logs\app.log";
    static readonly long maxSizeBytes = 5 * 1024 * 1024; // 5 MB

    static void Main()
    {
        Log("This is a log entry.");
    }

    static void Log(string message)
    {
        try
        {
            // Check file size
            if (File.Exists(logPath))
            {
                var fileInfo = new FileInfo(logPath);
                if (fileInfo.Length > maxSizeBytes)
                {
                    // Rotate the log
                    string backupPath = logPath + "." + DateTime.Now.ToString("yyyyMMdd_HHmmss");
                    File.Move(logPath, backupPath);
                }
            }

            // Append log
            File.AppendAllText(logPath, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}{Environment.NewLine}");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Logging failed: " + ex.Message);
        }
    }
}
```

### Behavior:

1. When `app.log` exceeds 5 MB:
2. It’s renamed (e.g., `app.log.20250513_161230`).
3. A **new empty** `app.log` is started.

### Variants:

1. **Truncate file** instead of rotating:
2. **Delete old logs** after N days or keep only the last N files.
3. Would you like a full logging utility class with rotation, size control, and thread-safety?

```cs
File.WriteAllText(logPath, ""); // clear the file
```

## Answers

### Answer by ICSM Computer

To **restrict the size of a log file** in C#, you typically check the file size **before writing**, and take action if it exceeds a limit — like **rotating**, **truncating**, or **archiving** the file.

### Example: Limit log file to 5 MB

```cs
using System;
using System.IO;

class Program
{
    static readonly string logPath = @"C:\Logs\app.log";
    static readonly long maxSizeBytes = 5 * 1024 * 1024; // 5 MB

    static void Main()
    {
        Log("This is a log entry.");
    }

    static void Log(string message)
    {
        try
        {
            // Check file size
            if (File.Exists(logPath))
            {
                var fileInfo = new FileInfo(logPath);
                if (fileInfo.Length > maxSizeBytes)
                {
                    // Rotate the log
                    string backupPath = logPath + "." + DateTime.Now.ToString("yyyyMMdd_HHmmss");
                    File.Move(logPath, backupPath);
                }
            }

            // Append log
            File.AppendAllText(logPath, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}{Environment.NewLine}");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Logging failed: " + ex.Message);
        }
    }
}
```

### Behavior:

1. When `app.log` exceeds 5 MB:
2. It’s renamed (e.g., `app.log.20250513_161230`).
3. A **new empty** `app.log` is started.

### Variants:

1. **Truncate file** instead of rotating:
2. **Delete old logs** after N days or keep only the last N files.
3. Would you like a full logging utility class with rotation, size control, and thread-safety?

```cs
File.WriteAllText(logPath, ""); // clear the file
```


---

Original Source: https://www.mindstick.com/interview/34108/how-can-you-restrict-file-size-when-writing-to-a-log-file

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
