Caching is an important technique for improving application performance and reducing unnecessary work. Most developers are familiar with memory caching and distributed caching solutions such as Redis. However, these approaches are not always suitable for every application.
Consider a command-line tool that developers use to analyze project files, generate reports, or validate configuration settings. The tool may need to retrieve metadata, process configuration information, or download reference data before performing its main operation. If the tool runs without an internet connection, it may not be able to retrieve the information it needs.
A file-based cache provides a practical solution to this problem. Instead of depending on a remote service or keeping everything in memory, an application can store reusable data on the local filesystem and load it during subsequent executions.
This approach is particularly useful for offline developer tools, build utilities, command-line applications, local automation scripts, and background processing services.
In this article, we will explore how to build a file-based cache in C# using .NET. We will implement a reusable caching service, manage expiration, handle concurrent access, and discuss production considerations for applications that must continue working without an internet connection.
Understanding File-Based Caching in .NET
A file-based cache stores application data in local files so that it can be reused later.
For example, imagine a developer tool that retrieves package metadata from a remote service. The metadata may not change frequently, but retrieving it every time the tool starts creates unnecessary network requests.
Instead, the application can save the retrieved information as a JSON file.
During the next execution, the application checks whether the cached file exists and whether it is still valid. If the cached information is available, it can use that information without contacting the remote service.
The basic workflow looks like this:
- Check whether the cache file exists.
- Read the cached data if it is available.
- Check whether the cached data has expired.
- Return valid cached data.
- Retrieve fresh data when the cache is unavailable or expired.
- Save the newly retrieved data for future use.
Unlike an in-memory cache, file-based caching allows data to remain available even after the application process terminates.
File-Based Cache vs. Memory Cache
Both approaches improve performance, but they solve slightly different problems.
| Feature | Memory Cache | File-Based Cache |
|---|---|---|
| Storage | Application memory | Local filesystem |
| Survives application restart | No | Yes |
| Access speed | Generally faster | Depends on storage |
| Memory consumption | Increases with cached data | Uses disk storage |
| Offline availability | Available while cached in memory | Available across executions |
| Sharing between processes | Requires additional coordination | Possible with synchronization |
| Implementation | Relatively simple | Requires file management |
Memory caching is useful for frequently accessed information during an application's lifetime. File-based caching is more suitable when data must survive application restarts or remain available offline.
For some applications, combining both approaches provides a better result.
Creating a File-Based Cache in C#
We will create a simple caching service that stores objects as JSON files.
The implementation will support:
- Saving objects to local files.
- Reading cached objects.
- Checking cache expiration.
- Removing expired entries.
- Handling missing or invalid cache files.
First, create a console application:
dotnet new console -n FileCacheTool
cd FileCacheToolFor this example, we will use the built-in System.Text.Json library, so no additional NuGet package is required.
Creating a Cache Model
A cache entry should contain more than just the original data. It should also store information about when the data was created.
Create a generic cache entry model:
public class CacheEntry<T>
{
public T? Data { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset ExpiresAt { get; set; }
}The CreatedAt property records when the cached information was generated.
ExpiresAt determines when the application should consider the entry invalid.
Using DateTimeOffset instead of DateTime makes the stored timestamps easier to handle consistently across environments with different time zones.
Implementing the File-Based Cache Service
Now we will create a reusable service that handles cache operations.
The service will accept a cache directory during initialization. Each cache key will represent a separate JSON file.
using System.Text.Json;
public class FileCacheService
{
private readonly string _cacheDirectory;
private readonly JsonSerializerOptions _options =
new()
{
PropertyNameCaseInsensitive = true
};
public FileCacheService(string cacheDirectory)
{
_cacheDirectory = cacheDirectory;
Directory.CreateDirectory(_cacheDirectory);
}
private string GetCachePath(string key)
{
string safeKey = Convert.ToHexString(
System.Security.Cryptography.SHA256.HashData(
System.Text.Encoding.UTF8.GetBytes(key)));
return Path.Combine(
_cacheDirectory,
safeKey + ".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,
_options);
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,
_options);
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;
}
}
public void Remove(string key)
{
string path = GetCachePath(key);
if (File.Exists(path))
{
File.Delete(path);
}
}
}Let's understand the important implementation decisions.
The constructor creates the cache directory if it does not already exist. This removes the need for 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 being interpreted as directory paths or filenames.
The SetAsync method creates a CacheEntry object and serializes it into JSON. The expiration timestamp is stored alongside the actual data.
The GetAsync method checks whether the file exists, reads its contents, and validates its expiration time before returning the cached object.
If the JSON is corrupted or cannot be deserialized, the implementation removes the invalid file and returns a cache miss.
For production use, the exception-handling strategy should also include logging. Unexpected permission errors and storage failures should not silently disappear.
Using the Cache Service in an Application
Now that the cache service is ready, we can use it to store information that may be required during offline execution.
Consider a developer tool that maintains package information.
Create a model:
public class PackageInfo
{
public string PackageName { get; set; } = string.Empty;
public string Version { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}We can now use the cache service:
var cache = new FileCacheService(
Path.Combine(
Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData),
"DeveloperTool",
"Cache"));
const string cacheKey = "package-metadata";
var cachedPackages =
await cache.GetAsync<List<PackageInfo>>(cacheKey);
if (cachedPackages == null)
{
Console.WriteLine("Cache not available.");
var packages = new List<PackageInfo>
{
new()
{
PackageName = "Newtonsoft.Json",
Version = "13.0.3",
Description = "JSON framework for .NET"
}
};
await cache.SetAsync(
cacheKey,
packages,
TimeSpan.FromDays(7));
cachedPackages = packages;
}
foreach (var package in cachedPackages)
{
Console.WriteLine(
$"{package.PackageName} - {package.Version}");
}In this example, the application checks the local cache before using package information.
If the information is available and has not expired, the application can continue without accessing an external service.
If the cache is missing, the example creates sample data and stores it locally.
In a real application, the sample data creation would be replaced with a remote retrieval operation when connectivity is available.
The important design decision is that the application should not assume that an internet connection will always be available.
Supporting Offline-First Execution
A file-based cache becomes particularly valuable when an application must continue operating without network connectivity.
However, caching and offline-first design are not exactly the same thing.
Caching provides previously stored information. Offline-first design requires the application to define what operations remain possible without external services.
For example, consider a developer tool that generates project reports using package metadata.
Its offline behavior might follow this approach:
- Use fresh cached metadata when available.
- Use expired cached metadata when the application is offline and stale data is acceptable.
- Retrieve updated metadata when connectivity is available.
- Report missing information when neither the cache nor the remote service can provide it.
This requires the application to distinguish between a missing cache entry and an expired cache entry.
The previous implementation treats both situations as cache misses. A more advanced implementation should return cache status information such as Fresh, Expired, Missing, or Invalid.
This allows the application to make better decisions when working without connectivity.
Handling Concurrent File Access
One important problem with file-based caching appears when multiple operations attempt to access the same cache entry simultaneously.
For example, two background tasks may try to update the same JSON file at the same time.
This can cause incomplete writes, file access exceptions, or corrupted cache contents.
A practical improvement is to write data to a temporary file first and then replace the destination file.
public async Task WriteCacheFileAsync(
string path,
string json,
CancellationToken cancellationToken = default)
{
string temporaryPath = path + "." +
Guid.NewGuid().ToString("N") + ".tmp";
try
{
await File.WriteAllTextAsync(
temporaryPath,
json,
cancellationToken);
File.Move(
temporaryPath,
path,
overwrite: true);
}
finally
{
if (File.Exists(temporaryPath))
{
File.Delete(temporaryPath);
}
}
}The temporary file is created in the same directory as the destination. This generally makes replacement operations more practical on the same filesystem.
However, atomic replacement behavior depends on the operating system and filesystem. If multiple processes can update the same cache key, temporary files alone are not enough. Use an appropriate cross-process locking strategy or a storage mechanism designed for concurrent access.
For a single-process application, a keyed SemaphoreSlim can provide additional protection around individual cache operations.
Best Practices for Production Applications
Use a Dedicated Cache Directory
Avoid storing cache files alongside application binaries or user project files.
Use an appropriate operating-system application data directory. For user-specific tools, LocalApplicationData is often a suitable choice.
Set Expiration Policies
Not every cached item needs the same expiration period.
Frequently changing metadata may require a shorter lifetime, while relatively stable reference information may remain useful for longer periods.
Choose expiration according to the data's business requirements.
Validate Cached Data
A cache file should not automatically be considered valid simply because it exists.
Validate its structure, version, expiration information, and required fields before using it.
Implement Cache Versioning
When the structure of cached objects changes, older JSON files may no longer be compatible.
Include a cache format version so that the application can identify outdated entries and regenerate them when necessary.
Handle Disk Space Carefully
Unlike memory caches, file-based caches can continue growing across application executions.
Implement cleanup policies that remove expired or unused entries. Consider a maximum cache size for tools that store large datasets.
Protect Sensitive Information
Do not store passwords, access tokens, or other sensitive information in ordinary JSON cache files.
Local files may be accessible to other processes or users depending on operating-system permissions. Use appropriate encryption and access controls when sensitive data must be stored.
Support Cancellation
Long-running cache operations should accept CancellationToken where appropriate.
This is especially useful when cache files are large or the tool processes multiple files.
Common Mistakes When Implementing File-Based Caching
| Mistake | Why It Matters | Recommended Solution |
|---|---|---|
| Using arbitrary cache keys as filenames | May create invalid or unsafe paths | Normalize or hash keys |
| Ignoring expiration | Returns outdated information | Store and validate expiration timestamps |
| Writing directly to existing files | Failed writes may leave incomplete content | Use temporary files |
| Ignoring corrupted JSON | Can repeatedly break application startup | Validate and remove invalid entries |
| Allowing unlimited cache growth | Consumes unnecessary disk space | Implement cleanup policies |
| Ignoring concurrent access | Can cause file conflicts | Use synchronization |
| Storing sensitive information | Creates security risks | Apply suitable protection |
| Depending only on cached data | Missing entries can break offline operations | Define an explicit offline fallback strategy |
Summary
Building a file-based cache in .NET is a practical way to make developer tools more efficient and reliable, especially when they need to operate without an internet connection.
By combining System.Text.Json, FileStream or File operations, expiration metadata, and proper resource management, developers can create a reusable caching mechanism without introducing an external caching dependency.
A well-designed file cache should do more than simply save and retrieve JSON files. It should also handle expired entries, corrupted data, concurrent access, cache versioning, and disk space management.
For command-line tools, local automation utilities, and offline developer applications, file-based caching provides a simple foundation for storing reusable information across application executions. When implemented with appropriate validation and synchronization, it can make applications more resilient and reduce unnecessary dependence on remote services.

Join the conversation! Your thoughts help the community grow.