Introduction
Caching is an important technique for improving application performance and reducing unnecessary operations. Most .NET applications use caching to avoid repeatedly retrieving the same information from databases, APIs, or other external services. However, not every application runs in an environment where a network connection is always available.
Consider a .NET command-line tool used by developers to analyze project files, generate reports, or process configuration data. The tool may need information that was previously downloaded from an external service. If the network becomes unavailable, the application may fail even when the required information was already retrieved during an earlier execution.
A file-based cache provides a practical solution to this problem. Instead of keeping cached information only in application memory, the application stores it on the local file system. The cached information remains available even after the application closes or the computer restarts.
In this article, we will explore how to build a file-based cache in .NET, store and retrieve cached data using JSON, manage expiration, handle corrupted cache files, and apply practical techniques for building reliable offline tools.
What Is a File-Based Cache?
A file-based cache stores frequently used information in files on the local system. When an application needs particular data, it first checks whether a valid cached copy exists.
If the information is available and has not expired, the application reads it from the cache. Otherwise, it retrieves the latest information from its original source and saves a new copy.
For example, a developer tool might download package metadata from an external service. Instead of downloading the same metadata every time the tool starts, it can store the response locally.
The next execution can use the cached information without making another network request.
A typical file-based caching workflow looks like this:
The application receives a request for particular data.
It checks whether the corresponding cache file exists.
It verifies whether the cached information is still valid.
If valid, it reads and returns the cached data.
If unavailable or expired, it retrieves fresh data from the original source.
It saves the new information and returns it to the caller.
This approach is particularly useful for command-line tools, desktop utilities, local development environments, and applications that need limited offline functionality.
Creating a File-Based Cache in .NET
We will build a simple cache service using C# and System.Text.Json. The service will store objects as JSON files inside a dedicated directory.
Each cached entry will contain the original data and the time when it was created.
Defining the Cache Entry Model
Start by creating a class that represents a cached item.
public class CacheEntry<T>
{
public T? Data { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset ExpiresAt { get; set; }
}
The Data property contains the information that the application wants to cache.
CreatedAt records when the cache entry was created, while ExpiresAt determines when the entry should no longer be considered valid.
Using DateTimeOffset instead of DateTime helps maintain consistent time information when applications run across different time zones.
Implementing the Cache Service
Now create a FileCacheService class that handles storing and retrieving cached information.
using System.Text.Json;
public class FileCacheService
{
private readonly string _cacheDirectory;
private readonly JsonSerializerOptions _jsonOptions =
new(JsonSerializerDefaults.Web);
public FileCacheService(string cacheDirectory)
{
_cacheDirectory = cacheDirectory;
Directory.CreateDirectory(_cacheDirectory);
}
private string GetCachePath(string key)
{
string fileName = Convert.ToHexString(
System.Security.Cryptography.SHA256.HashData(
System.Text.Encoding.UTF8.GetBytes(key)
)
);
return Path.Combine(_cacheDirectory, fileName + ".json");
}
public async Task SetAsync<T>(
string key,
T data,
TimeSpan expiration)
{
var entry = new CacheEntry<T>
{
Data = data,
CreatedAt = DateTimeOffset.UtcNow,
ExpiresAt = DateTimeOffset.UtcNow.Add(expiration)
};
string path = GetCachePath(key);
string json = JsonSerializer.Serialize(
entry,
_jsonOptions
);
await File.WriteAllTextAsync(path, json);
}
public async Task<T?> GetAsync<T>(string key)
{
string path = GetCachePath(key);
if (!File.Exists(path))
{
return default;
}
try
{
string json = await File.ReadAllTextAsync(path);
var entry = JsonSerializer.Deserialize<CacheEntry<T>>(
json,
_jsonOptions
);
if (entry == null ||
entry.ExpiresAt <= DateTimeOffset.UtcNow)
{
File.Delete(path);
return default;
}
return entry.Data;
}
catch (JsonException)
{
File.Delete(path);
return default;
}
catch (IOException)
{
return default;
}
}
}
Let's understand some important implementation decisions.
The constructor creates the cache directory if it does not already exist. This avoids requiring developers to create the directory manually before using the service.
The GetCachePath method converts the cache key into a SHA-256 hash. This prevents arbitrary cache keys from becoming file names and reduces problems caused by invalid file-system characters.
SetAsync serializes the cache entry into JSON and writes it to the local file system.
GetAsync checks whether the file exists, reads the stored information, and verifies its expiration time. If the entry has expired or contains invalid JSON, the method removes it and returns the default value.
The implementation handles common file and JSON errors, but a production cache may need additional protection against concurrent access and interrupted writes.
Using the Cache Service in a .NET Application
Consider a command-line tool that retrieves package information from an external service.
We can use the file cache to avoid downloading the same information repeatedly.
First, define a model:
public class PackageInfo
{
public string Name { get; set; } = string.Empty;
public string Version { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}
Next, create a method that checks the cache before making an external request.
public class PackageService
{
private readonly FileCacheService _cache;
private readonly HttpClient _httpClient;
public PackageService(
FileCacheService cache,
HttpClient httpClient)
{
_cache = cache;
_httpClient = httpClient;
}
public async Task<PackageInfo?> GetPackageAsync(string packageName)
{
string cacheKey = $"package:{packageName}";
var cachedPackage =
await _cache.GetAsync<PackageInfo>(cacheKey);
if (cachedPackage != null)
{
Console.WriteLine("Using cached package information.");
return cachedPackage;
}
try
{
var package = await _httpClient.GetFromJsonAsync<PackageInfo>(
$"https://example.com/packages/{Uri.EscapeDataString(packageName)}"
);
if (package != null)
{
await _cache.SetAsync(
cacheKey,
package,
TimeSpan.FromHours(12)
);
}
return package;
}
catch (HttpRequestException)
{
Console.WriteLine("Unable to retrieve package information.");
return null;
}
}
}
The application first checks the local cache. If the package information exists, it returns the cached object without making an HTTP request.
If the cache does not contain valid information, the application attempts to retrieve the latest data from the external service.
One important detail is that the example returns null when the network request fails and no valid cached entry exists. A production application should distinguish between missing data, expired data, and network failures so that callers can make appropriate decisions.
Handling Cache Files Safely
Writing JSON directly to a cache file is simple, but it can introduce problems when the application stops unexpectedly during a write operation.
For example, if the application crashes while writing a large JSON document, the cache file may contain incomplete data.
A safer approach is to write the new content to a temporary file and then replace the original file.
The following implementation demonstrates the basic pattern:
public async Task WriteCacheSafelyAsync(
string path,
string json)
{
string temporaryPath = path + ".tmp";
await File.WriteAllTextAsync(
temporaryPath,
json
);
File.Move(
temporaryPath,
path,
overwrite: true
);
}
Writing the temporary file first reduces the chance of leaving a partially written cache entry at the original path.
For stronger durability requirements, applications should also consider flushing data to storage and handling temporary files left behind after an interrupted operation.
When multiple processes access the same cache directory, additional coordination is necessary. Atomic replacement alone does not prevent two processes from overwriting each other's updates.
File-Based Cache vs Memory Cache
Both file-based and memory-based caching improve application performance, but they solve different problems.
Feature | Memory Cache | File-Based Cache |
|---|
Storage | Application memory | Local file system |
Survives application restart | No | Yes |
Access speed | Generally faster | Depends on file size and storage |
Offline availability | Only during the current process lifetime | Across application restarts |
Storage capacity | Limited by available memory | Depends on available disk space |
Management | Managed through cache APIs | Requires file management |
Suitable for | Temporary application data | Persistent local data |
Memory caching is suitable when data is needed only while an application is running.
File-based caching is more appropriate when information should remain available between executions.
For some applications, combining both approaches provides better results. Frequently accessed information can be kept in memory while the file system maintains a persistent copy.
Best Practices for Building a Reliable File Cache
Use a Dedicated Cache Directory
Avoid storing cache files directly inside the application installation directory.
Use an application-specific data directory instead. For example, .NET provides Environment.SpecialFolder.LocalApplicationData for user-specific local application storage.
string cacheDirectory = Path.Combine(
Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData
),
"MyDeveloperTool",
"Cache"
);
This keeps cached information separate from application binaries and makes it easier to manage application data.
Define Expiration Policies
Cached information should not remain valid forever unless the application explicitly requires permanent storage.
Choose expiration periods based on how frequently the original information changes.
Configuration metadata may remain valid for several hours, while frequently changing information may require a shorter expiration period.
Handle Corrupted Files
Cache files should always be treated as recoverable data rather than permanent application records.
Handle malformed JSON, missing files, permission errors, and unexpected file-system conditions without crashing the entire application.
Avoid Storing Sensitive Information
Do not store access tokens, passwords, or confidential information in ordinary cache files without appropriate protection.
Use secure storage mechanisms for sensitive credentials and apply suitable file permissions to cached application data.
Clean Up Expired Entries
Expired files should not accumulate indefinitely.
A maintenance process can periodically scan the cache directory, inspect expiration timestamps, and remove outdated entries.
This is particularly important for developer tools that generate many cache entries over time.
Use Unique Cache Keys
Cache keys should represent the actual data being stored.
For example, caching package information using only a generic key such as package may cause different packages to overwrite each other.
Use descriptive keys such as package:Newtonsoft.Json:13.0.3.
Common Mistakes to Avoid
One common mistake is treating cached information as the original source of truth. A cache can become outdated or corrupted, so applications should always have a clear recovery strategy.
Another mistake is using the same cache key for different data types or different versions of a resource. This can result in incorrect deserialization or unexpected application behavior.
Developers should also avoid writing directly to shared cache files without considering concurrent access. Two application instances may attempt to update the same file at the same time.
Finally, do not assume that a file-based cache automatically makes an application fully offline. The application must also have access to all the information and functionality required for offline operation.
Advantages and Disadvantages
Advantages
Cached information remains available after application restarts.
Reduces repeated network requests and unnecessary data downloads.
Does not require an external caching server.
JSON files make cached data easy to inspect during development.
Works well for command-line tools and desktop applications.
Supports offline access to previously retrieved information.
Disadvantages
File access is generally slower than memory access.
Applications must manage expiration and cleanup.
Concurrent file access requires additional coordination.
Cache corruption and file permission issues must be handled.
Large cache directories can consume significant disk space.
Sensitive cached information requires additional security measures.
Summary
A file-based cache is a practical solution for .NET applications that need persistent access to previously retrieved information. Unlike memory caching, cached data remains available even after the application closes or the system restarts.
By combining C#, System.Text.Json, and basic file-system operations, developers can build a lightweight caching service without depending on an external caching infrastructure.
A reliable implementation should include expiration handling, safe file writing, unique cache keys, error handling, and periodic cleanup. Applications that share cache files across multiple processes should also implement suitable concurrency controls.
For developer tools and applications that need to operate with limited network connectivity, file-based caching provides a simple way to improve responsiveness and support access to previously downloaded information.
Join the conversation! Your thoughts help the community grow.