---
title: "How do you implement a file-based cache system?"  
description: "How do you implement a file-based cache system?"  
author: "Ravi Vishwakarma"  
published: 2025-05-13  
updated: 2025-05-13  
canonical: https://www.mindstick.com/interview/34116/how-do-you-implement-a-file-based-cache-system  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 4 minutes  

---

# How do you implement a file-based cache system?

Implementing a **file-based cache system** in C# allows you to store and retrieve data on disk efficiently, which is useful for scenarios like:

1. Caching API responses
2. Storing expensive computation results
3. Avoiding redundant downloads or processing

### Basic Structure

1. A simple file-based cache can:
2. Use the **filename as a key**.
3. Store serialized data (e.g., JSON or binary).
4. Check timestamps or a TTL (time-to-live) to determine staleness.

![How do you implement a file-based cache system?](https://www.mindstick.com/interviewquestion/8f81a2aa-394b-4b15-b6be-ebada9654145/images/e555e49e-4ffe-43f7-86a4-aed9549deb93.png)

### Step-by-Step Implementation

```cs
using System;
using System.IO;
using System.Text.Json;

public class FileCache
{
    private readonly string _cacheDir;
    private readonly TimeSpan _defaultTtl;

    public FileCache(string cacheDir, TimeSpan? ttl = null)
    {
        _cacheDir = cacheDir;
        _defaultTtl = ttl ?? TimeSpan.FromMinutes(30);
        Directory.CreateDirectory(_cacheDir);
    }

    private string GetCachePath(string key)
    {
        string safeName = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(key));
        return Path.Combine(_cacheDir, safeName + ".json");
    }

    public void Set<T>(string key, T value)
    {
        var path = GetCachePath(key);
        var cacheItem = new CacheItem<T>
        {
            Timestamp = DateTime.UtcNow,
            Value = value
        };

        File.WriteAllText(path, JsonSerializer.Serialize(cacheItem));
    }

    public bool TryGet<T>(string key, out T value)
    {
        var path = GetCachePath(key);
        value = default;

        if (!File.Exists(path))
            return false;

        try
        {
            var json = File.ReadAllText(path);
            var cacheItem = JsonSerializer.Deserialize<CacheItem<T>>(json);

            if (DateTime.UtcNow - cacheItem.Timestamp < _defaultTtl)
            {
                value = cacheItem.Value;
                return true;
            }
            else
            {
                File.Delete(path); // Cache expired
            }
        }
        catch
        {
            // corrupted cache file or deserialization failure
            File.Delete(path);
        }

        return false;
    }

    private class CacheItem<T>
    {
        public DateTime Timestamp { get; set; }
        public T Value { get; set; }
    }
}
```

### Usage Example

```cs
var cache = new FileCache("cache");

string key = "user_profile_123";

if (cache.TryGet(key, out string profileJson))
{
    Console.WriteLine("Cache hit: " + profileJson);
}
else
{
    // Simulate slow data fetch
    profileJson = "{ \"name\": \"John\" }";
    cache.Set(key, profileJson);
    Console.WriteLine("Cache miss. Data fetched and cached.");
}
```

### Features You Can Add:

1. TTL per entry
2. Custom serialization (binary or XML)
3. Compression (e.g., GZip)
4. Max file count or max total size limit
5. Cleanup policy (oldest files deleted when disk use is high)

## Answers

### Answer by Ravi Vishwakarma

Implementing a **file-based cache system** in C# allows you to store and retrieve data on disk efficiently, which is useful for scenarios like:

1. Caching API responses
2. Storing expensive computation results
3. Avoiding redundant downloads or processing

### Basic Structure

1. A simple file-based cache can:
2. Use the **filename as a key**.
3. Store serialized data (e.g., JSON or binary).
4. Check timestamps or a TTL (time-to-live) to determine staleness.

![How do you implement a file-based cache system?](https://www.mindstick.com/interviewquestion/8f81a2aa-394b-4b15-b6be-ebada9654145/images/e555e49e-4ffe-43f7-86a4-aed9549deb93.png)

### Step-by-Step Implementation

```cs
using System;
using System.IO;
using System.Text.Json;

public class FileCache
{
    private readonly string _cacheDir;
    private readonly TimeSpan _defaultTtl;

    public FileCache(string cacheDir, TimeSpan? ttl = null)
    {
        _cacheDir = cacheDir;
        _defaultTtl = ttl ?? TimeSpan.FromMinutes(30);
        Directory.CreateDirectory(_cacheDir);
    }

    private string GetCachePath(string key)
    {
        string safeName = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(key));
        return Path.Combine(_cacheDir, safeName + ".json");
    }

    public void Set<T>(string key, T value)
    {
        var path = GetCachePath(key);
        var cacheItem = new CacheItem<T>
        {
            Timestamp = DateTime.UtcNow,
            Value = value
        };

        File.WriteAllText(path, JsonSerializer.Serialize(cacheItem));
    }

    public bool TryGet<T>(string key, out T value)
    {
        var path = GetCachePath(key);
        value = default;

        if (!File.Exists(path))
            return false;

        try
        {
            var json = File.ReadAllText(path);
            var cacheItem = JsonSerializer.Deserialize<CacheItem<T>>(json);

            if (DateTime.UtcNow - cacheItem.Timestamp < _defaultTtl)
            {
                value = cacheItem.Value;
                return true;
            }
            else
            {
                File.Delete(path); // Cache expired
            }
        }
        catch
        {
            // corrupted cache file or deserialization failure
            File.Delete(path);
        }

        return false;
    }

    private class CacheItem<T>
    {
        public DateTime Timestamp { get; set; }
        public T Value { get; set; }
    }
}
```

### Usage Example

```cs
var cache = new FileCache("cache");

string key = "user_profile_123";

if (cache.TryGet(key, out string profileJson))
{
    Console.WriteLine("Cache hit: " + profileJson);
}
else
{
    // Simulate slow data fetch
    profileJson = "{ \"name\": \"John\" }";
    cache.Set(key, profileJson);
    Console.WriteLine("Cache miss. Data fetched and cached.");
}
```

### Features You Can Add:

1. TTL per entry
2. Custom serialization (binary or XML)
3. Compression (e.g., GZip)
4. Max file count or max total size limit
5. Cleanup policy (oldest files deleted when disk use is high)


---

Original Source: https://www.mindstick.com/interview/34116/how-do-you-implement-a-file-based-cache-system

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
