Sa.Data.TempFolder
0.20.0
dotnet add package Sa.Data.TempFolder --version 0.20.0
NuGet\Install-Package Sa.Data.TempFolder -Version 0.20.0
<PackageReference Include="Sa.Data.TempFolder" Version="0.20.0" />
<PackageVersion Include="Sa.Data.TempFolder" Version="0.20.0" />
<PackageReference Include="Sa.Data.TempFolder" />
paket add Sa.Data.TempFolder --version 0.20.0
#r "nuget: Sa.Data.TempFolder, 0.20.0"
#:package Sa.Data.TempFolder@0.20.0
#addin nuget:?package=Sa.Data.TempFolder&version=0.20.0
#tool nuget:?package=Sa.Data.TempFolder&version=0.20.0
Sa.Data.TempFolder
English | Русский
Temporary directory management: path-guarded subfolders under a root, debounced activity marking of written folders, age-based background cleanup, low-priority volume tracking with an edge-triggered limit event, and optional free-space watching. Native AOT-safe, keyed multi-instance registration.
Table of Contents
- Overview
- Installation
- Quick Start
- API
- Path rules
- Cleanup
- Debounced activity marking
- Volume tracking
- Free space
- Background service
- Read-only mode
- Options Reference
- Error Handling
- FilePathResolver
Overview
AddSaTempFolder registers one (or several) keyed ITempFolder instances — a root directory plus the strategies and policies configured for it:
- Path guard — every path argument resolves through
PathGuard: it may be relative or absolute, but the result must stay inside the root;..segments and injection-style characters (~,>, shell metacharacters, control/invisible Unicode) are rejected (SecurityException). A path that passes through a symbolic link or junction inside the root is rejected too — for every operation, deletion and reading included. - Age-based cleanup — an expired top-level subfolder goes wholesale; a fresh one is descended into, and the same rule applies at every inner level, so date hierarchies (
yyyy/MM/dd/HH…) shed their old day/hour folders while the year/month containers stay (prefix-filtered at the top level, budget-capped, oldest first,Retry.Linearon transient I/O errors). Loose files directly in the root are never touched. - Date naming —
Naming = Datenames folders{FolderPrefix}+{current time shaped by FolderNameFormat}(any ofyyyy-MM-dd,yyyy-MM-dd/HH,yyyy/MM/dd,yyyy/MM/dd/HH,yyyyMMdd,yyyyMMdd/HH,yyyyMM/dd,yyyyMM/dd/HH…) — a readable hierarchy the cleanup can age level by level.GuidV7stays the default. - Debounced activity marking — a burst of accesses (writes and successful reads) re-arms one timer per touched folder; only a quiet period of
TouchDebounceactually refreshes the last write time of the accessed file's own directory and every ancestor up to the root, so active hierarchies survive cleanup at every level. - Cleanup yields to reads, writes, deletes and enumerations — an in-flight
WriteAsync/CopyFileAsync/ReadAsync/DeleteFileAsync/CreateSubfolder/EnumerateFilesAsynccancels the cleanup pass: a pass never starts while an operation runs (it returns 0), one already running when an operation arrives ends by cancellation at its next checkpoint, and a folder whose debounced marker touch has not landed yet is skipped — a just-accessed file is never deleted. - Overwrite policy —
WriteAsync/CopyFileAsyncreplace an existing target by default; setOverwriteFiles = falseto fail the write withIOExceptioninstead (the original stays intact). - Volume tracking — an optional low-priority background scan (
ThreadPriority.BelowNormal) measures the whole root, caches per-folder sizes keyed by the folder's last write time, and firesOnVolumeExceedededge-triggered (once over the limit, once back under). The event only notifies — nothing is deleted because of the volume itself. - Free-space watching — off by default; with
MinFreeSpace > 0the service polls the free space of the root's volume (first check at host start, then everyFreeSpaceCheckInterval, 24 h by default) and firesOnFreeSpaceReachededge-triggered when the reading reaches the limit. - Fail-fast startup — the background service access-checks every root (create / list / write probe) before the loops start.
Installation
dotnet add package Sa.Data.TempFolder
Quick Start
using Sa.Data.TempFolder;
builder.Services.AddSaTempFolder("uploads", b => b.Options(ob => ob.Configure(options =>
{
options.RootPath = "/var/tmp/uploads";
options.MaxAge = TimeSpan.FromHours(6);
options.FolderPrefix = "up_";
})));
Resolve it as a keyed service (a bare GetRequiredService<ITempFolder>() does not resolve keyed services):
var temp = sp.GetRequiredKeyedService<ITempFolder>("uploads");
var jobDir = temp.CreateSubfolder("jobs/42");
var (relative, absolute) = await temp.WriteAsync(stream, "jobs/42/payload.bin", ct);
var found = await temp.ReadAsync("jobs/42/payload.bin", async (s, ct) => await s.CopyToAsync(output, ct), ct);
var removedFile = await temp.DeleteFileAsync("jobs/42/payload.bin", ct);
await foreach (var file in temp.EnumerateFilesAsync("*.part", "jobs", recursive: true, ct)) { … }
var removed = await temp.CleanupExpiredAsync(ct);
The configure callback receives the ITempFolderBuilder: the section comes from FromConfiguration("…"), lowest-precedence per-registration defaults from Defaults(…), and the standard Configure / PostConfigure / Validate methods are reached through Options(...) — there is no bespoke options overload.
From configuration
{
"TempFolder": {
"RootPath": "/var/tmp/uploads",
"MaxAge": "06:00:00",
"FolderPrefix": "up_",
"CleanupInterval": "01:00:00",
"TrackVolume": true,
"MaxTotalSize": 10737418240
}
}
builder.Services.AddSaTempFolder("uploads", b => b.FromConfiguration("TempFolder"));
Scalar values bind from the section; OnVolumeExceeded and OnFreeSpaceReached are code-only channels and are never produced by configuration binding. Section binding runs first — after the Defaults(...) channel — so a Configure inside Options(...) always wins over configuration.
Defaults
A component that registers a temp folder on the caller's behalf can seed a property on the lowest-precedence channel with Defaults(...); both a value from the section and a code Configure override it, so a default never steals an explicit setting:
builder.Services.AddSaTempFolder("uploads", b => b
.Defaults(o => o.MaxAge = TimeSpan.FromDays(30)) // applied only when nothing else sets MaxAge
.FromConfiguration("TempFolder"));
Several instances
builder.Services.AddSaTempFolder("uploads", b => b.FromConfiguration("TempFolder:Uploads"));
builder.Services.AddSaTempFolder("exports", b => b.Options(ob => ob.Configure(o => o.MaxAge = TimeSpan.FromMinutes(30))));
var uploads = sp.GetRequiredKeyedService<ITempFolder>("uploads");
var exports = sp.GetRequiredKeyedService<ITempFolder>("exports");
Each call gets its own named options instance (sections and Configure callbacks never stack across registrations). Registering the same name twice throws at registration time.
Code overrides
builder.Services.AddSaTempFolder("special", b => b
.UseCleanupStrategy<EverythingExpiredStrategy>() // wins over the Cleanup enum
.UseNamingStrategy<JobFolderNameStrategy>()); // wins over the Naming enum
The overridden type is registered as one instance per registration (its dependencies resolve from the container) and mapped onto this instance's keyed strategy slot — a stateful strategy never leaks state across instances. Built-ins are selected by the Cleanup / Naming enums: AgeBased + GuidV7 by default, or AgeBased + Date (with FolderNameFormat) when configured:
builder.Services.AddSaTempFolder("byday", b => b.Options(ob => ob.Configure(o =>
{
o.Naming = TempFolderNamingKind.Date; // folders like "up_2026/10/08/14"
o.FolderNameFormat = "yyyy/MM/dd/HH"; // any .NET date/time format
o.FolderPrefix = "up_"; // lands on the first segment
})));
The format is rendered with the invariant culture for the container's TimeProvider (local time), and its rendered shape is validated along with the prefix — a broken or injection-style format fails with OptionsValidationException at resolve/start.
API
| Member | Description |
|---|---|
Name / RootPath |
Registration key and the fully qualified root. |
CreateSubfolder(rel?) |
Creates a subfolder (parents included) — rel relative or absolute (inside the root). Without an argument the name comes from the naming strategy: GuidV7 → {FolderPrefix}{guid-v7:N} (time-sortable, collision-free); Date → {FolderPrefix}{FolderNameFormat} (calls within one format bucket share the folder). |
WriteAsync(stream, path, ct) |
Writes a stream into a file — path relative or absolute (inside the root) — creating parents, and (debounced) activates the touched folder chain. Overwrites an existing file unless OverwriteFiles = false. When the source's remaining length is known (CanSeek), the target is preallocated to exactly that size. The copy is staged in a sibling temp file and renamed into place only when complete: a reader never observes a truncated target, and a failed or cancelled copy leaves an existing file exactly as it was (the staged partial is removed). Returns (RelativePath, AbsolutePath). |
CopyFileAsync(src, subfolder?, ct) |
Copies an external file in — subfolder relative or absolute (inside the root); without a subfolder a fresh strategy-named one is built and the file keeps its own name (the name itself must pass the path rules). Same overwrite policy as WriteAsync. |
ReadAsync(path, loadStream, ct) |
Reads a file through the callback — path relative or absolute (inside the root). Returns true when a file was found and handed to loadStream (false when there is not — the callback is never invoked). The whole read is one activity against cleanup: a concurrent pass is cancelled instead of reading over a deletion. Only the open of the file may race a vanish; a FileNotFoundException raised by the callback itself propagates to the caller unchanged. A successful read also refreshes (debounced) the activity markers of the file's directory chain, exactly like a write — a folder that is only ever read from does not age out. Allowed on a read-only instance. |
DeleteFileAsync(path, ct) |
Deletes a single file — path relative or absolute (inside the root). Folders are never removed: a path that points at a directory throws InvalidOperationException (expired subfolders go through CleanupExpiredAsync, not here), and the file's subfolder is left in place until the pass ages it out. Returns true when a file existed and was removed, false when there is none (or it vanished concurrently). One activity against cleanup like the other operations; transient failures are retried (Retry.Linear, 3 attempts) and rethrown as IOException when exhausted. Read-write instances only. |
EnumerateFilesAsync(pattern, subfolder?, recursive?, ct) |
Asynchronously enumerates matching files, returns absolute paths. subfolder relative or absolute (inside the root); pattern is a pattern, not a path, so */? are allowed there. Symbolic links and junctions are skipped — neither reported nor descended into, so every returned path really lives under the root. The whole enumeration is one activity against cleanup: the pass cannot delete folders out from under the walk. |
CleanupExpiredAsync(ct) |
Runs one cleanup pass; returns the number of folders actually deleted (always 0 for a read-only instance; a candidate that vanished out-of-band is not counted). Yields to reads, writes, deletes and enumerations: cancelled (0) while one is in flight, interrupted when one starts mid-pass, folders with a pending activity touch skipped. |
EnsureAccessAsync(ct) |
Verifies the root: creates it when missing (read-write only), lists it, and runs a write/create/delete probe. |
Path rules
Every path argument (rel, path, subfolder, path) goes through PathGuard before touching the filesystem:
- Relative or absolute — both accepted. An absolute path is used as-is; it must resolve to the root itself or to a location under it, otherwise
SecurityException. Nothing is ever expanded:~/…is rejected, not rewritten to a home directory. ..is rejected as a segment on either separator, anywhere — evenjobs/../jobs/42, which would normalise to a path inside the root. No caller needs it in a temp path.- Injection-style characters are rejected with
SecurityException, before any normalisation:- ASCII control characters
0x00–0x1F/0x7F(NUL truncation,\t,\r,\n…); - shell/glob metacharacters
~ < > | & ; ` $ ^ * ? " ' %— redirection, pipes, command chaining/substitution, variable & environment expansion, quote breaking, globbing, and percent-encoded traversal (..%2f); - a literal
\on Unix (a Windows path or a shell escape smuggled into a Unix path); - Unicode format/control characters — zero-width space, bidi overrides (U+202E) and friends;
- on Windows: a colon outside the
C:drive spec (NTFS alternate data streams).
- ASCII control characters
- Normalisation still applies afterwards:
Path.GetFullPath+ a separator-aware containment check, so a sibling directory sharing the root's name prefix (/var/tmp/uploads_evilvs root/var/tmp/uploads) is never mistaken for a child. FolderPrefixobeys the same rules (validated at resolve/host start —OptionsValidationException). The enumerationpatternis exempt:*/?belong to patterns.- Symlinks are not traversed. A path is checked component by component, target included, for every operation — create, write, copy, read, delete, enumerate: if any existing component between the root and it is a symlink or junction, the operation fails with
SecurityException. A link planted inside the root (up_cache → /var/www) can neither redirect a write or a folder creation to its target, nor make a delete unlink a file outside the root, nor leak a read from there. Recursive enumeration skips reparse points entirely, so the paths it returns always live under the root and a link cycle cannot hang the walk.
Cleanup
One pass = strategy selection → guarded deletion:
- The strategy (
AgeBasedby default) selects subfolders whose age exceedsMaxAge, oldest first across all levels. The age comes fromAgeSource:LastWriteTime(default — refreshed by the debounce on writes) orCreationTime. The per-pass budget (MaxFoldersPerPass) is enforced by the instance: a built-in strategy already caps its list, and a custom one returning more is truncated to the firstMaxFoldersPerPassentries — oldest first is what leaves the freshest expired folders for the next pass. - The descent rule: an expired top-level subfolder (filtered by
FolderPrefix) goes wholesale with everything inside it; a top-level subfolder that is still fresh is descended into, and the same rule applies at every inner level recursively. That is what makes date hierarchies work —2026stays for a year while its long-old months inside are shed, and an expired month takes its days with it without anyone walking them first. The prefix filter applies to top-level folders only (nested folders are the instance's own structure — re-filtering them by prefix would exempt every inner level); a non-prefixed top-level folder is skipped and not descended into. The descent stops at depth 16 and skips folders that vanish or turn unreadable mid-pass. A symlinked (or junction) folder is skipped entirely — neither selected nor descended into: its content belongs to the link's target, which may live anywhere on disk, and deleting a candidate inside it would delete in the target's tree. - The instance re-validates every returned path against the root (a hostile strategy cannot escape), deletes with
Retry.Linear(3 attempts, transientIOException/UnauthorizedAccessExceptiononly) and counts the result. - The pass yields to file activity. A
WriteAsync/CopyFileAsync/ReadAsync/DeleteFileAsync/CreateSubfolder/EnumerateFilesAsyncin flight (or a pending marker walk) cancels the pass outright — it returns 0 and the next interval retries. A read, write or delete arriving mid-pass cancels the pass token instead: the deletion ends by cancellation at its next checkpoint, and the operation proceeds the moment the pass unwinds. A folder whose debounced touch has not landed yet is skipped explicitly — a file accessed moments ago is never taken together with its folder.
Deleted → LogInformation; a folder that survives the retries → LogWarning, the pass continues. Files directly in the root are out of scope.
Turning the cleanup off
CleanupEnabled = false switches deletion off entirely: the background service starts no cleanup loop, and CleanupExpiredAsync returns 0 without touching the disk. The instance stays fully writable (writes are allowed) — unlike read-only, which refuses writes too.
builder.Services.AddSaTempFolder("uploads", b => b.Options(ob => ob.Configure(o =>
{
o.CleanupEnabled = false; // the folder's lifecycle belongs to someone else
})));
What does not change: the volume tracking and the free-space check — they only report and never delete, so their loops keep running and OnVolumeExceeded / OnFreeSpaceReached keep firing. A manual CleanupExpiredAsync call also still measures the volume first and only then returns 0, so even with the default VolumeScanInterval = 0 (scan only before a cleanup pass) the limit stays watched and the event keeps firing.
While the cleanup is off, its knobs (MaxAge, MaxFoldersPerPass, CleanupInterval) are not read: a zero is accepted there (an explicit "not used"), a negative value is an error either way. MaxAge = 0 with the cleanup enabled is a validation error: zero would mean "everything is expired", and the first pass would wipe the root.
Debounced activity marking
With AgeSource=LastWriteTime an actively accessed folder (written to or read from) must not look expired — at any level of the hierarchy. After every write or successful read one timer per touched folder (the accessed file's own directory) is armed: further accesses within TouchDebounce (default 5 s) re-arm it, and only a quiet period of that length sets LastWriteTimeUtc = "now" — for that directory and every ancestor up to (excluding) the root, one level at a time. The chain matters because overwrites alone never move a directory's mtime, and because the nested cleanup ages intermediate levels too: a file landing in up_2026/10/08/14/f.bin keeps 14, 08, 10 and up_2026 fresh. The instance root itself is never touched. Pending touches are dropped on dispose (the folders simply stay older — the safe direction). The walk itself rides the same exclusion as reads, writes and deletes — a cleanup pass can never overlap it — and the pending entry clears only after the walk has landed; that is exactly what lets cleanup tell "just accessed, spare it" (skip) from "quiet for ages, take it" (delete).
Volume tracking
Off by default: with TrackVolume=false the volume is never computed and MaxTotalSize is inert. When on (and MaxTotalSize > 0):
- The measurement runs on a dedicated background thread at
ThreadPriority.BelowNormal, so walking a large tree never preempts request work. - Per-folder sizes are cached by the folder's last write time; only touched or modified folders are re-walked. Symbolic links are never followed or counted — top-level or nested — so a planted link cannot inflate the total with someone else's bytes, and a link cycle cannot spin the walk.
- The scan runs before every cleanup pass, plus its own interval when
VolumeScanInterval > 0(default0= scan only before cleanup). OnVolumeExceededis edge-triggered: it fires once when the total crossesMaxTotalSizeand once when it falls back under — never repeatedly while the state holds. A first reading already under the limit stays silent (there is no transition to announce); a first reading over the limit fires at once. The transition is also logged (Warning/Information). Handler exceptions are caught and logged. Nothing is deleted because of the volume — cleanup stays age-based; the event is for the subscriber (metrics, admin action, adaptive throttling). Writes and deletions performed through the instance invalidate the affected cache entry immediately: a deep change never moves the top-level folder's stamp, and overwriting a file moves no stamp at all, so the next scan re-measures instead of serving the pre-change total.
options.OnVolumeExceeded = e =>
metrics.TempExceeded(e.Name, e.TotalSize, e.MaxTotalSize, e.Exceeded);
Free space
Off by default: with MinFreeSpace = 0 (the default) the volume is never probed. When a limit is set, the background service runs one check per instance:
- The probe is a single volume stat (
DriveInfoagainst the root's volume — on Unix the root path itself, so the reading stays on its actual mount; on Windows the drive root). No tree walk, no thread; a probe failure (volume gone, permission denied) is logged by the loop and retried at the next interval. - The schedule is
FreeSpaceCheckInterval(24 h by default): the first check runs right at host start — an already-tight volume must surface immediately, not after a day — then once per interval. OnFreeSpaceReachedis edge-triggered likeOnVolumeExceeded: it fires once when the reading drops to or belowMinFreeSpace(Reached = true) and once when it climbs back above (Reached = false) — never repeatedly while the state holds, so a daily poll cannot spam the subscriber. A first reading above the limit stays silent (nothing has been reached yet); a first reading already at the limit fires at once. Transitions are logged (Warning/Information); handler exceptions are caught and logged. Nothing is deleted because of the free space — the event is for the subscriber (metrics, alerts, draining the folder).
builder.Services.AddSaTempFolder("uploads", b => b.Options(ob => ob.Configure(o =>
{
o.MinFreeSpace = 5L * 1024 * 1024 * 1024; // 5 GiB
o.OnFreeSpaceReached = e =>
alerts.TempFreeSpace(e.Name, e.AvailableFreeSpace, e.MinFreeSpace, e.Reached);
})));
Background service
One TempFolderCleanerHost per service collection walks all registrations:
- At start —
EnsureAccessAsyncfor every instance; a broken root fails host startup with a clear message instead of surfacing at first use. - Then — one cleanup loop per instance (
CleanupInterval, first pass after one interval) and, when configured, one volume-scan loop (VolumeScanInterval, first pass immediately) and one free-space loop (FreeSpaceCheckInterval, first pass immediately). The cleanup loop is started only while the cleanup is enabled (CleanupEnabled) — a disabled cleanup deletes nothing, while the volume-scan and free-space loops keep running. Pass failures are logged and never bring the host down; all delays use the container'sTimeProvider, so tests can virtualise the schedule.
Read-only mode
ReadOnly=true puts the instance into read mode:
CreateSubfolder/WriteAsync/CopyFileAsync/DeleteFileAsyncthrowInvalidOperationException— reading (ReadAsync) and enumeration keep working, they mutate nothing.CleanupExpiredAsyncreturns0, and the background service ignores the instance entirely — no cleanup, no volume scan, no event, no free-space check.- Startup validation then checks only that the root exists and can be listed (it is never created).
- Not the same as a disabled cleanup: read-only refuses writes as well, while
CleanupEnabled = falseleaves the instance fully writable.
Options Reference
| Option | Default | Description |
|---|---|---|
RootPath |
Path.GetTempPath() |
Root directory; relative values are resolved to a full path before validation. When it equals the system temp directory, FolderPrefix must be non-empty — an unscoped cleanup there would delete other processes' folders (validation fails otherwise). |
MaxAge |
24 h | Age after which a subfolder is expired (see AgeSource). Must be positive while the cleanup is enabled; a zero is accepted with the cleanup off (no TTL). |
AgeSource |
LastWriteTime |
LastWriteTime | CreationTime. |
FolderPrefix |
"" |
Name prefix for generated folders and the cleanup filter (plain name — ./.., separators and path-rule characters rejected). With Naming = Date it lands on the first segment of the date path (up_ + yyyy/MM/dd → up_2026/10/08). Required (non-empty) when RootPath is the system temp directory. |
FolderNameFormat |
yyyy-MM-dd |
.NET date/time format Naming = Date shapes folder names with — invariant culture, container's TimeProvider, local time. Works with any pattern (yyyy-MM-dd/HH, yyyy/MM/dd, yyyyMMdd, yyyyMM/dd/HH …); the rendered shape is validated with the prefix (broken format, .., rooted output → OptionsValidationException). |
OverwriteFiles |
true |
WriteAsync / CopyFileAsync replace an existing target file; false → the write fails with IOException and the original stays intact. |
MaxFoldersPerPass |
100 | Upper bound of deletions per cleanup pass; enforced by the instance, so it caps a custom strategy's output too. |
CleanupInterval |
1 h | Background cleanup period per instance. |
CleanupEnabled |
true |
Whether the instance deletes expired subfolders at all. false → no cleanup loop is started and CleanupExpiredAsync returns 0; volume tracking and the free-space check keep running. See turning the cleanup off. |
VolumeScanInterval |
0 |
Independent volume-scan period; 0 = scan only before a cleanup pass. |
MinFreeSpace |
0 |
Minimum free bytes the root's volume should keep; 0 = the check is off and the volume is never probed. Positive → one check per FreeSpaceCheckInterval, firing OnFreeSpaceReached edge-triggered. |
FreeSpaceCheckInterval |
24 h | Free-space check period; first check at host start. Must be positive while MinFreeSpace > 0; with the check off a zero is accepted (an explicit "not used"). |
ReadOnly |
false |
See Read-only mode. |
TrackVolume |
false |
Measure and cache folder sizes at all. |
MaxTotalSize |
0 |
Volume limit in bytes; 0 = off. Exceeding fires the event only. |
TouchDebounce |
5 s | Quiet period before a file access (write or successful read) refreshes the activity markers of the touched folder chain (the file's own directory and every ancestor up to the root). |
Cleanup |
AgeBased |
Built-in cleanup strategy, overridable with UseCleanupStrategy<T>(). |
Naming |
GuidV7 |
GuidV7 | Date (with FolderNameFormat), overridable with UseNamingStrategy<T>(). |
OnVolumeExceeded |
null |
Code-only edge-triggered volume event; never bound from configuration. |
OnFreeSpaceReached |
null |
Code-only edge-triggered free-space event; never bound from configuration. |
Validation is an explicit IValidateOptions (ValidateOnStart()), not ValidateDataAnnotations() — the latter is RequiresUnreferencedCode (IL2026) and would break Native AOT.
Error Handling
| Situation | Behaviour |
|---|---|
Path resolves outside the root (.., sibling-prefix, absolute outside) |
SecurityException. |
.. segment or injection character in a path (~, >, shell metacharacters, control/invisible Unicode) |
SecurityException — rejected even when the path would have stayed inside the root. See Path rules. |
| Path passes through a symbolic link inside the root (create, write, copy, read, delete) | SecurityException — the link's target is never created in, written to, read from or deleted. |
| Absolute path argument that stays inside the root | Accepted like a relative one. |
| Operation on a read-only instance | InvalidOperationException for mutations — ReadAsync / EnumerateFilesAsync stay allowed. |
Target file exists and OverwriteFiles = false |
IOException from WriteAsync / CopyFileAsync — the original is left intact. |
ReadAsync with no file at the path |
Returns false — the callback is never invoked. A path pointing at a directory throws InvalidOperationException. |
ReadAsync callback throws (e.g. FileNotFoundException of its own) |
The exception propagates to the caller unchanged — only the open of this file reads "no file". |
WriteAsync / CopyFileAsync fails or is cancelled mid-copy |
The exception propagates; the staged partial is removed and the target is left as it was — an existing file is never truncated by a failed overwrite. |
DeleteFileAsync with no file at the path |
Returns false. A path pointing at a directory throws InvalidOperationException; a transient failure that survives the retries rethrows IOException. |
| Invalid options | OptionsValidationException at first resolve / host start — never at registration (includes a broken or injection-style FolderNameFormat). |
| Broken root at startup | InvalidOperationException from EnsureAccessAsync, failing host start. |
| Folder fails to delete after retries | LogWarning, counted as not deleted, the pass continues. |
| Cleanup pass starts while an operation is in flight | The pass is cancelled before selecting anything — returns 0, the next interval retries. |
| A read, write or delete arrives during a cleanup pass | The pass ends by cancellation at its next checkpoint (partial count returned); the operation proceeds after it unwinds. |
| A folder's debounced marker touch has not landed yet | The pass skips the folder — a just-accessed file is never deleted. |
| Strategy throws or returns an escaping path | Pass skipped (throw) or entry skipped (escape) with a log entry — never a crash. |
OnVolumeExceeded handler throws |
Caught and logged; the scan completes. |
OnFreeSpaceReached handler throws |
Caught and logged; the check completes. |
| Free-space probe fails (volume gone, permission denied) | Logged by the loop; retried at the next interval — the host stays up. |
FilePathResolver
Companion component of this package, namespace Sa.Data.TempFolder.FilePathResolver — its own
folder, with a dedicated readme: FilePathResolver/Readme.md
(Russian version).
Resolves fuzzy / imprecise paths (as stored in a database) into real paths on the file system. Every discovered mapping is cached per database path, so subsequent lookups are a dictionary read plus a single file probe.
Public surface: IFilePathResolver (the DI service type), FilePathResolver (the default
implementation, fluent configuration included) and IFileSystemService (the disk seam; the
disk-backed DefaultFileSystemService stays internal).
Resolution cascade (first hit wins):
- Direct — the database path is an absolute path that literally exists.
- Relative — the path exists relative to
ConfiguredPath. - Incremental — trailing components of the database directory are matched against
directories under
ConfiguredPath, innermost first — so a lost leading prefix (/storage/usbdisk1/mikopbx/astspool/monitor/2021/06/16/15/file.mp3→<root>/2021/06/16/15/file.mp3) still resolves. - Deep search (opt-in) — recursive search by file name. Hits are not cached: a file found anywhere in the tree carries no directory mapping.
| Method | Description |
|---|---|
ResolvePath(string, bool asRelativePath = false) |
Resolves the database path, or returns null when the file cannot be located. Throws ArgumentException on null/whitespace. |
WithPossibleExtensions(params string[]) |
Extensions tried during fuzzy search when the exact name misses ("mp3" and ".mp3" are equivalent). |
WithDeepSearch(bool) |
Enables / disables recursive search by file name. |
WithForceSearch(bool) |
When enabled, every call re-runs the full cascade instead of reading the per-file cache. |
WithMap(string) |
Explicit global mapping applied before the cascade: database paths starting with map are looked up directly under ConfiguredPath. |
IsResolved / IsDeepSearch / IsForceSearchEnabled |
Current resolver state. |
Resolved (event) |
Raised once, when the first mapping is established. |
var resolver = FilePathResolver.Create("/records")
.WithPossibleExtensions("mp3", "wav")
.WithDeepSearch(true);
// "/storage/usbdisk1/mikopbx/astspool/monitor/2021/06/16/15/has-root.mp3"
// → /records/2021/06/16/15/has-root.mp3 (directory-suffix match)
string? full = resolver.ResolvePath(dbPath);
string? rel = resolver.ResolvePath(dbPath, asRelativePath: true); // "2021/06/16/15/has-root.mp3"
Registration (keyed, as AddSaTempFolder)
| Call | Description |
|---|---|
services.AddFilePathResolver(name, configuredPath, configure?) |
Registers IFilePathResolver under name — one host can serve several named roots. |
services.AddFilePathResolver(configuredPath, configure?) |
The same under the default key Setup.DefaultName ("default", the resolver's Setup class in Sa.Data.TempFolder.FilePathResolver). |
sp.GetRequiredKeyedService<IFilePathResolver>(name) |
Resolves the instance — a bare GetRequiredService<IFilePathResolver>() does not resolve keyed services. |
- Registration names must be unique: a duplicate throws
InvalidOperationExceptionat registration; a null/whitespacenameorconfiguredPaththrowsArgumentException. - Registration is lazy: a root that does not exist surfaces as
DirectoryNotFoundExceptionat first resolve — never at registration. configureruns once, when the instance is built, and is the same fluent chain as direct construction:r => r.WithMap(...).WithPossibleExtensions(...).WithDeepSearch(true).- The disk seam resolves a keyed
IFileSystemServicefirst (per registration), then a plain one, and falls back to the disk-backed default.
builder.Services.AddFilePathResolver("records", "/data/records",
r => r.WithPossibleExtensions("mp3", "wav").WithDeepSearch(true));
// somewhere later:
var resolver = sp.GetRequiredKeyedService<IFilePathResolver>("records");
string? full = resolver.ResolvePath(dbPath);
string? rel = resolver.ResolvePath(dbPath, asRelativePath: true);
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.14)
- Microsoft.Extensions.Hosting.Abstractions (>= 10.0.14)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.14)
- Microsoft.Extensions.Options (>= 10.0.14)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 10.0.14)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Sa.Data.TempFolder:
| Package | Downloads |
|---|---|
|
Sa.HybridFileStorage.FileSystem
File storage management |
GitHub repositories
This package is not used by any popular GitHub repositories.