CkFile
Job: make file names and paths from the outside world safe to use — clean the name, read the extension, guard the path, decode base64 uploads — and keep the files themselves: write, read, copy, move and delete inside a named place, every file proven to be what its extension says.
Files reach an application as text: a name typed into a form, a path stored in a
database, an upload sent as base64. None of that text can be trusted as-is. CkFile
splits the work in two: FileName is a sanitizer — it repairs a name until it is safe
to save; RelativePath is a gate — a suspicious path is rejected outright, never
repaired. The standard rejection values apply: a string method answers "" (empty),
FromBase64 answers an empty byte array, and HasExtension answers false. Nothing
throws unless you ask (How it works).
The class also acts on files, inside a FilePlace alone —
Uploads, Temporary, Images, Videos, Audio, Media, Documents, Imports,
Exports, Archives, each a folder your application names once (Your file places, set once). Every
operation takes a place, Uploads unless said, and a relative path, holds the path to RelativePath's gate, and
never reaches outside the place's folder. A file lands in a place only when its extension
is one the place takes, its size is within the place's limit, and its content proves the
extension: a PHP script named scan.pdf never becomes a document. The rejection values
are the library's: false, "", an empty array, or null from the OrNull twins.
Quick look
using SafeCoder.CommonKit;
using SafeCoder.CommonKit.Enums;
CkFile.FileName("Report: Q3?.pdf"); // -> "Report_ Q3_.pdf"
CkFile.Extension("archive.tar.gz"); // -> "gz"
CkFile.RelativePath("a/../secrets.txt"); // -> "" (a climb — rejected)
CkFile.FromBase64("AQID"); // -> bytes { 1, 2, 3 }
CkFile.DataUriType("data:image/PNG;base64,iVBORw0KGgo"); // -> "image/png"
CkFile.IsRelativePath("a/../secrets.txt"); // -> false
CkFile.InMediaTypes(upload, "image/*"); // -> true for any image
CkFile.IsWithinSize(upload, 5 * 1024 * 1024); // -> true when 5 MB or less
CkFile.Combine(uploads, "../secrets.txt"); // -> "" (the join escapes the root)
CkFile.SizeToString(1536); // -> "1.5 KB"
CkFile.Explain("a/../b"); // -> the gate's reason
CkFile.Write(FilePlace.Documents, "claim-18/scan.pdf", bytes); // -> true (a PDF, within the limit, inside the place)
CkFile.Write(FilePlace.Documents, "claim-18/shell.php", bytes); // -> false (a blocked extension)
CkFile.Write(FilePlace.Images, "avatar.png", pdfBytes); // -> false (the content is a PDF)
CkFile.Read(FilePlace.Documents, "claim-18/scan.pdf"); // -> the bytes
CkFile.Move(FilePlace.Uploads, "7f3a.pdf", "claim-18/scan.pdf", into: FilePlace.Documents); // -> true (filed, after the same checks)
CkFile.SniffType(bytes); // -> "application/pdf", whatever the file was called
CkFile.IsAllowed(FilePlace.Images, "avatar.png", bytes); // -> true for a real PNG
CkFile.UniqueName("scan.pdf"); // -> "scan-3f9a1c7e.pdf"
Your file places, set once
A place is a kind of file, never a path. Your application says one root, and every
place is the subfolder named after it — D:\Files\Images, D:\Files\Audio,
D:\Files\Documents — made the first time something is written there. A place that
lives elsewhere gets a folder of its own instead. Beside the folder, two rules per place:
the extensions it takes and the most bytes a file may have. Three doors set all of it, a
later door overriding an earlier one key by key:
- In code,
CkSettings.DefaultFileRootfor the root, and per placeCkSettings.FileRoot(place)for a folder of its own,CkSettings.FileExtensions(place)andCkSettings.FileMaxBytes(place): eachnullas shipped. Fill one in with a literal, or with anything the base library can answer. -
In
appsettings.jsonbeside the application, the sectionCommonKit:Files:{ "CommonKit": { "Files": { "Root": "D:\\Files", "Documents": { "MaxBytes": 10485760, "Extensions": ["pdf", "docx", "csv"] }, "Archives": { "Root": "E:\\Archive" }, "Blocked": ["zip", "rar"] } } }Documents and Images live under
D:\FilesasDocumentsandImages; Archives has a folder of its own on another drive. -
Over it,
appsettings.{Environment}.json, the environment named byASPNETCORE_ENVIRONMENTorDOTNET_ENVIRONMENT, and over both, a variable —CommonKit__Files__Root,CommonKit__Files__Documents__Root,__MaxBytes,__Extensions(comma-separated),CommonKit__Files__Blocked— the host's own spelling of a section key.
The library reads the files and the variables itself, once, the first time a file
operation runs: a static class has no way to reach IConfiguration, and these two doors
need none. An application whose folders live elsewhere — user secrets, a vault — hands
them over as a process variable before its first file operation, or writes them into
FileRoot in its copy of CkSettings. Step by step, in a project of your own — the file,
the environment file, the variables, and the check that shows what reached the library:
Setting up your file places.
As shipped, no root and no folder is set, so nothing can touch a disk until you have
said where your files live; every place takes 2 MB (CkSettings.DefaultMaxFileBytes), and
the extensions it takes are the library's own:
| Place | Takes by default |
|---|---|
Images |
jpg, jpeg, png, gif, webp, bmp, tif, tiff, heic, avif |
Videos |
mp4, mov, webm, mkv, avi |
Audio |
mp3, wav, ogg, m4a, flac |
Media |
pictures, video and audio together |
Documents |
pdf, doc, docx, xls, xlsx, ppt, pptx, odt, ods, odp, rtf, txt, csv |
Imports |
csv, xlsx, xls, json, xml, txt |
Exports |
pdf, csv, xlsx, docx, json, zip |
Archives |
zip, 7z, rar, gz, tar |
Uploads, Temporary |
all of the above |
No place takes "anything", and svg is out of Images on purpose: it is XML that can
carry a script. AllowedExtensions and MaxBytes answer
the rules in force, for an upload form's accept attribute and its size hint.
Three rules stand whatever you set:
- A root that is a root is refused as if it were unset — the drive, the file system's
root, the application's own folder or one above it — and so is a place's own folder, so a
place is always a folder of its own and
../web.configis never in bounds. The shared root, or a place's own folder, must exist; the place's subfolder under the root, and everything inside it, the library makes as needed. - A file is always inside a place, never the place: a path that names the folder itself
is refused, and so is one that climbs out, exactly as
RelativePathrefuses it. - Blocked extensions are never taken, however a place is listed.
CkSettings.BlockedExtensionsnames them, each with what it is — programs, the scripts a system or a web server runs, the pages and scripts a browser runs, a web server's own files — and a refusal says so:a blocked extension (php, a script the web server runs). A blocked extension is refused anywhere in a name, since Apache runsshell.php.pdfas PHP by its first extension, and so is a longer extension whose first three characters are blocked, since a Windows short name keeps only those:shell.phpxisSHELL~1.PHP. The settings file and the variable can add to that list, never take from it; BlockedExtensions lists the ones in force. - A link below a place is never followed, in or out. A symbolic link or a junction
planted inside a place's folder — by an archive extracted there, by another account on a
shared host — would make the text of a path lie, so every operation refuses one wherever
it stands between the place's folder and the file:
a link inside the place (linkdir), which is never followed. The place's own folder may be a link. - A page is taken nowhere, under any name. Content a browser would run — HTML, an
XHTML-namespaced or stylesheet-bearing XML, an SVG — is refused even under an extension
you listed that the library has no type for, since a file served without a type is
sniffed by the browser. An extension you list is otherwise taken on your word, and
xmlorxsl, which browsers render, should not be among them for a folder the web server serves.
Methods
FileName
A name that is safe to save.
string FileName(
string? input = null,
string? fallback = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The raw value. |
fallback |
string? |
null |
Value to use when nothing usable survives. It goes through the same sanitizing and is never returned as typed; a fallback that is itself rejected answers "". |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering "", when neither the value nor the fallback can be used. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
The value (or the fallback) survives the sanitizing |
The safe name: "Report_ Q3_.pdf" |
The safe name: "Report_ Q3_.pdf" |
Rejected: missing, over CkSettings.MaxPathInputLength (1,024) characters, or nothing survives the sanitizing |
Empty string | Throws CkFileException — carries Input, Expected and Reason |
A sanitizer, not a validator — use RelativePath when the value claims to be a path.
Turns whatever arrives into a name any operating system will accept. The characters
Windows forbids (< > : " / \ | ? *) become underscores, trailing dots and spaces go,
and a name longer than 255 characters (CkSettings.MaxFileNameLength) is cut with its
extension kept — never through the middle of a character: an emoji is two chars, and a
cut between them would leave half of one, which no filesystem takes. Windows also reserves some device names — CON, PRN, NUL, COM1
and friends — that hang or misbehave when used as a file name, even with an extension;
those are defused with a leading underscore. This is a rename, not a rejection: the goal
is a name you can write to disk.
CkFile.FileName("Report: Q3?.pdf"); // -> "Report_ Q3_.pdf"
CkFile.FileName("CON.txt"); // -> "_CON.txt" (reserved name defused)
CkFile.FileName("invoice/2026.pdf"); // -> "invoice_2026.pdf" (a slash is not a name)
CkFile.FileName("..."); // -> "" (nothing survives — rejected)
Extension
What kind of file the name claims.
string Extension(
string? input = null,
string? fallback = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The raw file name or path. |
fallback |
string? |
null |
A file name to use when the value has no usable extension. It goes through the same reading and is never returned as typed; a fallback that is itself rejected answers "". |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering "", when neither the value nor the fallback has a usable extension. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
The value (or the fallback) has a usable extension |
The extension, lower-case and without the dot: "pdf" |
The extension, lower-case and without the dot: "pdf" |
| Rejected: missing, oversized, no dot, a dotfile, or an extension that is not letters and digits | Empty string | Throws CkFileException — carries Input, Expected and Reason |
With throwIfInvalid: true a dotfile throws too — no extension counts as a rejection here.
The extension of a file name or path — lower-case, without the dot, letters and digits
only. A path answers its last segment's extension; only the last extension counts. A
dotfile (a name starting with a dot, like .gitignore) and a name without a dot have
no extension and answer "".
CkFile.Extension("Report.PDF"); // -> "pdf"
CkFile.Extension("archive.tar.gz"); // -> "gz" (only the last)
CkFile.Extension("exports/2026/report.pdf"); // -> "pdf"
CkFile.Extension(".gitignore"); // -> "" (a dotfile has no extension)
HasExtension
The allow-list check.
bool HasExtension(
string? input = null,
params IEnumerable<string?> allowed
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The raw file name or path. |
allowed |
params IEnumerable<string?> |
— | The extensions to accept, compared without case or dots; null, empty and blank entries are skipped. |
Returns
| When | You get |
|---|---|
| The name's extension matches an entry on the list | true |
| No extension, an empty list, or no match | false — and it never throws |
No throwIfInvalid here (a params list must come last) — call Extension with it first when you need the error.
True when the name's extension is on your list. Entries are compared without case or
dots, so "pdf", ".PDF" and "Pdf" all mean the same thing. A name without an
extension, or an empty list, answers false.
CkFile.HasExtension(
input: "Report.PDF",
allowed: ["pdf", "docx"]
); // -> true
CkFile.HasExtension(
input: "photo.exe",
allowed: ["pdf", "docx"]
); // -> false
CkFile.HasExtension(
input: "scan.pdf",
allowed: [".PDF"]
); // -> true (dots and casing in entries are forgiven)
RelativePath
The path-traversal gate.
string RelativePath(
string? input = null,
string? fallback = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The raw path. |
fallback |
string? |
null |
A path to use when the value cannot be used. It goes through the same validation and is never returned as typed; a fallback that is itself rejected answers "". |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering "", when neither the value nor the fallback can be used. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
The value (or the fallback) stays inside its folder |
The tidied path, forward slashes only: "exports/2026/report.pdf" |
The tidied path, forward slashes only: "exports/2026/report.pdf" |
Rejected: missing, oversized, rooted, a drive or stream colon, a .. climb, a forbidden character, a segment starting with a space or ending in a dot or space, or a reserved Windows name in a segment |
Empty string | Throws CkFileException — carries Input, Expected and Reason |
Rejection over repair — a "fixed" hostile path is still hostile intent.
Validates a relative path you stored or received — "exports/2026/report.pdf" — as one
that stays inside its folder. Path traversal is the classic attack where a stored path
uses ".." (which means "the folder above") to climb out of the folder you meant and
reach files like system secrets. So this method rejects instead of repairing: a rooted
path (one starting with /), a drive or stream colon (C:), a ".." climb, a
forbidden character, a segment starting with a space or ending in a dot or space, or a reserved Windows name in
any segment rejects the whole value.
What passes is tidied — backslashes become forward slashes, "." segments and doubled
slashes collapse. Combine the result with your own base folder
(Path.Combine(baseDir, relative)); never accept an absolute path from data.
CkFile.RelativePath("exports\\2026\\report.pdf"); // -> "exports/2026/report.pdf"
CkFile.RelativePath("./a/./b.txt"); // -> "a/b.txt"
CkFile.RelativePath("a/../secrets.txt"); // -> "" (a climb — rejected)
CkFile.RelativePath("/etc/passwd"); // -> "" (rooted — rejected)
CkFile.RelativePath("C:\\temp\\x.txt"); // -> "" (drive colon — rejected)
FromBase64
Text back into bytes.
byte[] FromBase64(
string? input = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The base64 text, or a data URI holding one. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering an empty array, when the value cannot be decoded. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The text decodes | The bytes: { 1, 2, 3 } |
The bytes: { 1, 2, 3 } |
Rejected: missing, over CkSettings.MaxBase64InputLength (16,777,216) characters, a data URI without a base64 payload, an empty payload, or not valid base64 |
Empty array — never null |
Throws CkFileException — carries Input, Expected and Reason |
The declared media type of a data URI reads separately with DataUriType.
Decodes base64 text into a byte[]. Base64 is the standard way of writing bytes as
plain text — it is how file uploads travel inside JSON. This method reads plain base64,
the URL-safe alphabet (- and _ instead of + and /), unpadded text (missing =
signs at the end), and a full data URI like "data:image/png;base64,…" (the payload
after the comma). Whitespace inside is ignored. The answer is never null: an empty
array means the value was rejected — so "bytes came back" means it really decoded. What
counts as base64 is what IsBase64 counts: text whose last character carries
bits no byte can hold — "no", "US", a date — is refused, not read as the bytes a
lenient decoder would invent for it.
CkFile.FromBase64("AQID"); // -> bytes { 1, 2, 3 }
CkFile.FromBase64("data:image/png;base64,AQID"); // -> bytes { 1, 2, 3 }
CkFile.FromBase64("AQ"); // -> bytes { 1 } (unpadded is fine)
CkFile.FromBase64("not base64!"); // -> empty array — rejected
CkFile.FromBase64("2026-08-31"); // -> empty array — not base64, whatever a lenient decoder makes of it
DataUriType
What a data URI says it is.
string DataUriType(
string? input = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The data URI. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering "", when the value cannot be used. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The data URI declares a well-formed media type | The lowercase type: "image/png" |
The lowercase type: "image/png" |
| Rejected: missing, not a data URI, or no well-formed media type in it | Empty string | Throws CkFileException — carries Input, Expected and Reason |
Shape-checked, not verified — the type is what the sender claimed, not what the bytes are.
The media type a data URI declares — the label that says what kind of file it is, like
"image/png" — lowercased. The type is shape-checked: one name, one slash, letters,
digits and .+- only, so a stored value cannot smuggle markup into a Content-Type
header. Empty means the value is missing, is not a data URI, or declares no well-formed
type. Note the declared type is only a claim — it tells you what the sender said, not
what the bytes really are.
CkFile.DataUriType("data:image/PNG;base64,iVBORw0KGgo"); // -> "image/png"
CkFile.DataUriType("data:;base64,AAAA"); // -> "" (no type declared)
CkFile.DataUriType("just text"); // -> ""
IsSafeFileName
Already a name FileName would leave alone?
bool IsSafeFileName(
string? input = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The raw file name. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering false, when the value is not a safe name as written. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
The cleaned value equals what FileName would make of it |
true |
true |
FileName would have to change it — a forbidden character, a reserved name, a trailing dot, over-long |
false |
Throws — the reason says what it would become |
| An invisible character in the name — a zero-width space, a soft hyphen, a bidi mark, a control character | false |
Throws — "an invisible character in the name: FileName would remove it" |
| Rejected: nothing usable at all | false |
Throws CkFileException — carries Input, Expected and Reason |
A shape check for intake policies that reject rather than repair. Surrounding whitespace
and markup are cleaned away first, as every shape check does; then the name must be
exactly what FileName would produce. "who?.pdf" is false, and with the
flag the reason reads FileName would change it to "who_.pdf". An invisible character is
the one thing the cleaning is not allowed to excuse: "report.pdf" cleans to
"report.pdf" and looks like it, but it is a different name and a different file, so it is
false — the name as written is what is judged.
CkFile.IsSafeFileName("Report Q3.pdf"); // -> true
CkFile.IsSafeFileName("who?.pdf"); // -> false
CkFile.IsSafeFileName("con.txt"); // -> false (a reserved name)
CkFile.IsSafeFileName("report.pdf"); // -> false (a zero-width space inside)
IsRelativePath
Does it pass the traversal gate?
bool IsRelativePath(
string? input = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The raw path. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering false, when the value is not a safe relative path. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
Relative, no drive or stream colon, no .. climb, no forbidden character, no reserved segment |
true |
true |
| Rejected: any of those | false |
Throws CkFileException — carries Input, Expected and Reason |
The yes-or-no form of RelativePath, for validation code; call the gate itself when you want the normalized path back. A bare file name is a relative path.
CkFile.IsRelativePath("exports/2026/report.pdf"); // -> true
CkFile.IsRelativePath("a/../secrets.txt"); // -> false (a climb)
CkFile.IsRelativePath("/etc/passwd"); // -> false (rooted)
IsBase64
Does the text decode?
bool IsBase64(
string? input = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The base64 text or data URI. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering false, when the value is not base64. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| Plain, URL-safe or unpadded base64, or a data URI with a base64 payload, decoding to at least one byte | true |
true |
| Rejected: not base64, an empty payload, a data URI without base64, over the cap | false |
Throws CkFileException — carries Input, Expected and Reason |
The yes-or-no form of FromBase64, judged without allocating the bytes: the same shaping — whitespace ignored, the URL-safe alphabet mapped, padding restored — then the framework's own validity check. An empty payload is not a file, so it is false.
CkFile.IsBase64("SGVsbG8"); // -> true (unpadded is fine)
CkFile.IsBase64("data:text/plain,hello"); // -> false (no base64 payload)
CkFile.IsBase64("AAAAA"); // -> false (a length no base64 has)
IsDataUri
A data URI with a file in it?
bool IsDataUri(
string? input = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The raw value. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering false, when the value is not such a data URI. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
The data: prefix, a well-shaped media type, ;base64, and a payload that decodes to at least one byte |
true |
true |
| Rejected: not a data URI, no type, no base64, an empty or invalid payload | false |
Throws CkFileException — carries Input, Expected and Reason — the reason says which |
Everything an upload field should carry, in one check. A plain-text data URI
(data:text/plain,hello) is false, as FromBase64 treats it. The type is shape-checked,
not verified against the bytes; see InMediaTypes to allow-list it.
CkFile.IsDataUri("data:image/png;base64,iVBORw0KGgo"); // -> true
CkFile.IsDataUri("data:;base64,AQID"); // -> false (no type)
CkFile.IsDataUri("data:image/png;base64,"); // -> false (an empty payload)
InMediaTypes
One of the types we accept?
bool InMediaTypes(
string? input = null,
params IEnumerable<string?> types
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The data URI. |
types |
params IEnumerable<string?> |
— | The media types to accept, type/subtype, type/* for a family, or */* for anything that has a type. Null, empty and blank entries are skipped. |
Returns
| When | You get |
|---|---|
| The value is a data URI whose declared type matches an entry | true |
| It is not a data URI, declares no well-formed type, no entry matches, or the list is empty | false — an answer, not a failure; it never throws |
The upload allow-list check, "images only". The declared type is read the way
DataUriType reads it, lowercase, and entries are compared the same way.
This judges the declared type alone — a well-shaped lie passes — so pair it with
IsDataUri for the payload and check the bytes when it matters. A params
list must be last, so there is no throwIfInvalid; call DataUriType with it first.
CkFile.InMediaTypes(upload, "image/png", "image/jpeg"); // -> true for a PNG
CkFile.InMediaTypes(upload, "image/*"); // -> true for any image type
CkFile.InMediaTypes("data:application/pdf;base64,…", "image/*"); // -> false
IsWithinSize
Small enough to accept?
bool IsWithinSize(
string? input = null,
long maxBytes = 0,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The base64 text or data URI. |
maxBytes |
long |
0 |
The largest decoded size allowed, in bytes. Below 0 acts as 0. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering false, when the value is not base64. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
Valid base64 that decodes to no more than maxBytes |
true |
true |
| Valid base64 that decodes to more | false |
false |
| Rejected: not base64 | false |
Throws CkFileException — carries Input, Expected and Reason |
The "uploads up to 5 MB" rule, worked out from the text alone: base64 length maps to byte count exactly once padding is accounted for, so nothing is decoded and the check is cheap enough to run before anything is. Too big is an answer, not an error.
CkFile.IsWithinSize(upload, 5 * 1024 * 1024); // -> true when the file is 5 MB or less
CkFile.IsWithinSize("AQID", 2); // -> false (three bytes)
Combine
A full path that cannot escape its folder.
string Combine(
string? root = null,
string? relative = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
root |
string? |
null |
The folder everything must stay inside. |
relative |
string? |
null |
The stored or received relative path. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering "", when the root is missing, the relative path fails the gate, or the join escapes the root. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The relative path passes RelativePath's gate and the join stays inside the root | The full path, in the operating system's separators | The path |
| Rejected: no root, a path the gate refuses, a join that escapes | "" |
Throws CkFileException — carries Input, Expected and Reason |
The traversal-safe form of Path.Combine, which happily follows "../" out of the
folder. The gate runs first, then the joined path is resolved and checked to start inside
the root, so no spelling escapes.
CkFile.Combine(uploads, "2026/report.pdf"); // -> "/srv/uploads/2026/report.pdf"
CkFile.Combine(uploads, "../secrets.txt"); // -> ""
SizeToString
1.5 MB, as people read it.
string SizeToString(
object? bytes = null,
int decimals = 1,
string fallback = "",
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
bytes |
object? |
null |
The byte count: a number of any type, or text. |
decimals |
int |
1 |
The most decimal places to show, 0 to 3. |
fallback |
string |
"" |
What comes back when the count cannot be read. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering the fallback, when the count is not a whole, non-negative number. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| A whole, non-negative count | "512 B", "1.5 KB", "1 MB" — steps of 1024, halves rounded up, trailing zeros dropped |
The size |
| Rejected: negative, a fraction, junk | The fallback |
Throws CkFileException — carries Input, Expected and Reason |
The convention operating systems and browsers show.
CkFile.SizeToString(1536); // -> "1.5 KB"
CkFile.SizeToString(5242880); // -> "5 MB"
MediaType
The Content-Type a file name implies.
string MediaType(
string? input = null,
string? fallback = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The raw file name or path. |
fallback |
string? |
null |
The media type to answer for an unknown extension; "application/octet-stream" is the usual choice. Held to the bare type/subtype shape: parameters reject it rather than being dropped. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering "", when no media type can be answered. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The extension is in the table | The media type, lowercase: "application/pdf" |
The type |
| It is not, and a well-formed fallback is given | The fallback | The fallback |
| Rejected: no extension, an unknown one with no fallback, a fallback that is not a media type | "" |
Throws CkFileException — carries Input, Expected and Reason |
A fixed table of the common document, image, audio, video, archive, font and web formats, read the way Extension reads the extension.
CkFile.MediaType("Report.PDF"); // -> "application/pdf"
CkFile.MediaType("data.xyz", fallback: "application/octet-stream"); // -> "application/octet-stream"
ToDataUri
Bytes as a data URI.
string ToDataUri(
byte[]? bytes = null,
string? type = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
bytes |
byte[]? |
null |
The file bytes. |
type |
string? |
null |
The media type, e.g. "image/png", bare — no parameters — see MediaType. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering "", when there are no bytes or the type is not well-formed. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| Bytes and a well-formed type | "data:image/png;base64,…" |
The URI |
| Rejected: no bytes, a malformed type | "" |
Throws CkFileException — carries Input, Expected and Reason |
The reverse of FromBase64, for embedding a file in JSON, HTML or a mail.
CkFile.ToDataUri(bytes, CkFile.MediaType("photo.png")); // -> "data:image/png;base64,…"
FullPath
The full path of a relative path inside a place.
string FullPath(
FilePlace place = FilePlace.Uploads,
string? relative = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place the path is inside. |
relative |
string? |
null |
The relative path. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering "", when the place has no folder or the path fails the gate. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The place has a folder, the path passes RelativePath's gate and resolves inside it | The full path, in the operating system's form | The path |
| Rejected: no folder set for the place, a path the gate refuses, the folder itself | "" |
Throws CkFileException — carries Input, Expected and Reason |
Combine for a named place. Nothing is read or written and the file need not exist: this is the path to hand to something else that reads or writes the file — a stream, a framework's own storage.
CkFile.FullPath(FilePlace.Images, "2026/logo.png"); // -> "D:\Files\Images\2026\logo.png" on a Windows server
CkFile.FullPath(FilePlace.Images, "../web.config"); // -> "" (the gate)
CkFile.FullPath(FilePlace.Videos, "clip.mp4"); // -> "" (no folder is set for Videos)
Exists
Whether a file is there.
bool Exists(
FilePlace place = FilePlace.Uploads,
string? relative = null
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place to look in. |
relative |
string? |
null |
The relative path of the file. |
Returns true when a file is at the path; false for a folder, for nothing there,
for a path the gate refuses, and for a place with no folder. A validator: it never throws.
CkFile.Exists(FilePlace.Documents, "claim-18/scan.pdf"); // -> true when the file is there
CkFile.Exists(FilePlace.Documents, "claim-18"); // -> false (a folder)
Size
A file's size, in bytes.
long Size(
FilePlace place = FilePlace.Uploads,
string? relative = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place the file is in. |
relative |
string? |
null |
The relative path of the file. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering 0, when there is no such file. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| A file is at the path | Its size in bytes | The size |
| Rejected: no such file, a folder, the gate, no folder set for the place | 0 |
Throws CkFileException |
An empty file is 0 as well; SizeOrNull tells the two apart.
CkFile.SizeToString(CkFile.Size(FilePlace.Documents, "claim-18/scan.pdf")); // -> "1.2 MB"
SizeOrNull
A file's size, or null when there is no such file.
long? SizeOrNull(
FilePlace place = FilePlace.Uploads,
string? relative = null
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place the file is in. |
relative |
string? |
null |
The relative path of the file. |
Returns the size in bytes, or null when there is no such file, the path names a
folder, the gate refuses it, or the place has no folder — so an empty file, which is 0,
is told from a missing one. Never throws.
Files
The files in a folder of a place.
string[] Files(
FilePlace place = FilePlace.Uploads,
string? folder = null
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place. |
folder |
string? |
null |
The relative path of the folder; null or empty for the place itself. |
Returns the files' relative paths inside the place, with forward slashes, sorted — ready for Read, Move or Delete. Files alone, not folders or links, and not the temporary names a write in progress uses. Empty when the folder is missing, the path fails the gate, or the place has no folder. Never throws.
CkFile.Files(FilePlace.Documents, "claim-18"); // -> ["claim-18/estimate.pdf", "claim-18/scan.pdf"]
Read
A file's bytes.
byte[] Read(
FilePlace place = FilePlace.Uploads,
string? relative = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place the file is in. |
relative |
string? |
null |
The relative path of the file. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering empty, when the file could not be read. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| A file is at the path, within the place's limit | Its bytes | The bytes |
| Rejected: no such file, a folder, over the limit, the gate, no folder set for the place | an empty array | Throws CkFileException |
The file is read whole, so one over the place's limit (MaxBytes) is refused rather than loaded: serve a large file through FullPath and a stream. An empty file reads as empty too; ReadOrNull tells the two apart.
byte[] scan = CkFile.Read(FilePlace.Documents, "claim-18/scan.pdf");
CkFile.Read(FilePlace.Documents, "missing.pdf"); // -> [] (nothing there)
ReadOrNull
A file's bytes, or null when there is no such file.
byte[]? ReadOrNull(
FilePlace place = FilePlace.Uploads,
string? relative = null
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place the file is in. |
relative |
string? |
null |
The relative path of the file. |
Returns the bytes, or null when there is no such file, the path names a folder, the
gate refuses it, the place has no folder, or the file is over the place's limit — so an
empty file, which reads as an empty array, is told from a missing one. Never throws.
Write
Bytes to a file inside a place, checked first.
bool Write(
FilePlace place = FilePlace.Uploads,
string? relative = null,
byte[]? bytes = null,
bool overwrite = false,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place to write in. |
relative |
string? |
null |
The relative path of the file. |
bytes |
byte[]? |
null |
The file's content. |
overwrite |
bool |
false |
Pass true to replace an existing file; by default one is refused. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering false, when the file could not be written. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The file is in place | true |
true |
Rejected: no folder set for the place, the gate, an existing file without overwrite, a folder at the path, no bytes, an extension the place does not take or a blocked one, over the limit, content that does not prove the extension |
false |
Throws CkFileException — the Reason says which |
The way a payload's base64 lands on disk: FromBase64, then this. The
file's folders are created when missing, and the bytes are written beside the destination
under a temporary name and renamed into place once complete, so the path never names a
half-written file. The place's rules are applied before a byte is written: the extension
must be one the place takes and never a blocked one, the bytes within the place's limit,
and the content must prove the extension — a PNG named scan.pdf is refused as such, and
so is an empty file, which proves nothing. A staged upload is named with the extension it
claims, 7f3a.pdf, so it is checked once, on arrival.
byte[] scan = CkFile.FromBase64(payload.Scan);
CkFile.Write(FilePlace.Documents, "claim-18/scan.pdf", scan); // -> true (written)
CkFile.Write(FilePlace.Documents, "claim-18/scan.pdf", scan); // -> false (already there)
CkFile.Write(FilePlace.Documents, "claim-18/scan.pdf", scan, overwrite: true); // -> true (replaced)
CkFile.Write(FilePlace.Documents, "claim-18/shell.php", scan); // -> false (a blocked extension)
CkFile.Write(FilePlace.Images, "avatar.png", scan); // -> false (the content is a PDF)
Copy
A copy of a file, in the same place or another.
bool Copy(
FilePlace place = FilePlace.Uploads,
string? from = null,
string? to = null,
bool overwrite = false,
FilePlace? into = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place the source is in. |
from |
string? |
null |
The relative path of the file to copy. |
to |
string? |
null |
The relative path to copy it to, inside the destination place. |
overwrite |
bool |
false |
Pass true to replace an existing destination; by default one is refused. |
into |
FilePlace? |
null |
The place to copy into; null for the same place. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering false, when the copy could not be made. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The copy is in place | true |
true |
Rejected: no folder set for the place, the gate on either path, a source that is missing or a folder, an existing destination without overwrite, the same file, the destination's extension not taken or blocked, over the limit, content that does not prove the destination's extension |
false |
Throws CkFileException |
The copy is written beside the destination under a temporary name and renamed into place once complete, the destination's folders are created when missing, and the source is left as it was. The destination place's rules are applied to the destination, as Write applies them: its extensions, its limit, the content check.
CkFile.Copy(FilePlace.Documents, "incoming/scan.pdf", "claim-18/scan.pdf"); // -> true
CkFile.Copy(FilePlace.Documents, "incoming/scan.pdf", "claim-18/scan.pdf"); // -> false (the destination exists)
CkFile.Copy(FilePlace.Documents, "claim-18/scan.pdf", "scan.pdf", into: FilePlace.Temporary); // -> true (a copy in another place)
CkFile.Copy(FilePlace.Documents, "claim-18/scan.pdf", "scan.pdf", into: FilePlace.Images); // -> false (Images takes no PDF)
Move
A file moved, in the same place or into another — the filing of a staged upload.
bool Move(
FilePlace place = FilePlace.Uploads,
string? from = null,
string? to = null,
bool overwrite = false,
FilePlace? into = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place the source is in. |
from |
string? |
null |
The relative path of the file to move. |
to |
string? |
null |
The relative path to move it to, inside the destination place. |
overwrite |
bool |
false |
Pass true to replace an existing destination; by default one is refused, on every operating system alike. |
into |
FilePlace? |
null |
The place to move into; null for the same place. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering false, when the file could not be moved. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The file is at its new path | true |
true |
| Rejected: as for Copy | false |
Throws CkFileException |
The destination's folders are created when missing. The destination place's rules are applied to the destination — the check a staged upload gets when it is filed — and a move between two folders on one volume is a rename, whichever places they belong to.
CkFile.Move(FilePlace.Uploads, "7f3a.pdf", "claim-18/scan.pdf", into: FilePlace.Documents); // -> true (filed)
CkFile.Move(FilePlace.Uploads, "7f3a.pdf", "claim-18/scan.pdf", into: FilePlace.Documents); // -> false (the source is gone)
CkFile.Move(FilePlace.Documents, "claim-18/scan.pdf", "claim-18/scan-v2.pdf"); // -> true (a rename, same place)
Delete
A file deleted — true once it is gone.
bool Delete(
FilePlace place = FilePlace.Uploads,
string? relative = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place the file is in. |
relative |
string? |
null |
The relative path of the file. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering false, when the file could not be deleted. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| No file is at the path — deleted now, or never there | true |
true |
| Rejected: a folder at the path, the gate, no folder set for the place, a file that could not be deleted | false |
Throws CkFileException |
A file that was never there answers true, so a clean-up in a finally needs no
Exists first. Files alone: a path that names a folder is refused.
CkFile.Delete(FilePlace.Temporary, "7f3a.pdf"); // -> true (gone)
CkFile.Delete(FilePlace.Temporary, "7f3a.pdf"); // -> true (still gone)
IsAllowed
Whether a place would take a file.
bool IsAllowed(
FilePlace place = FilePlace.Uploads,
string? relative = null,
byte[]? bytes = null
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
place |
FilePlace |
FilePlace.Uploads |
The place. |
relative |
string? |
null |
The relative path the file would have. |
bytes |
byte[]? |
null |
The file's content; null to judge the name alone. |
Returns true when the place has a folder, the path passes the gate, its extension is
one the place takes and not a blocked one, and — when the bytes are given — they are within the place's limit and
their content proves the extension. The check a handler runs before Write, which
applies the same rules and says which failed when asked. Never throws.
CkFile.IsAllowed(FilePlace.Images, "avatar.png", bytes); // -> true for a PNG within the limit
CkFile.IsAllowed(FilePlace.Images, "avatar.php", bytes); // -> false (blocked)
CkFile.IsAllowed(FilePlace.Images, "avatar.png", pdfBytes); // -> false (the content is a PDF)
CkFile.IsAllowed(FilePlace.Images, "avatar.png"); // -> true (the name alone, judged)
These answers assume Images has a folder. As shipped no place has one, so every call
answers false until a root or the place's own folder is set — see
Setting up your file places.
AllowedExtensions
The extensions a place takes, in force.
string[] AllowedExtensions(FilePlace place = FilePlace.Uploads)
Returns the extensions as your application set them, or the library's own list for the
place when nothing is set (Your file places, set once):
lowercase, without dots, in the order set, never a blocked one. The list an upload form's
accept attribute is built from. Never throws; empty for a value that is no place.
CkFile.AllowedExtensions(FilePlace.Images); // -> ["jpg", "jpeg", "png", "gif", "webp", "bmp", "tif", "tiff", "heic", "avif"] as shipped
BlockedExtensions
The extensions no place takes, in force.
string[] BlockedExtensions()
Returns the library's own (CkSettings.BlockedExtensions) and those your application
added in its settings file or in a variable — additions only, the library's own are never
taken away. Sorted, lowercase, without dots. Never throws.
MaxBytes
The most bytes a file in a place may have, in force.
long MaxBytes(FilePlace place = FilePlace.Uploads)
Returns what your application set for the place, or CkSettings.DefaultMaxFileBytes,
2 MB, when nothing is set. What Write, Copy, Move and
Read hold a file to, and the number an upload form shows. Never throws; 0 for a
value that is no place.
SniffType
The media type a file's bytes prove, whatever the file was called.
string SniffType(
byte[]? bytes = null,
string? fallback = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
bytes |
byte[]? |
null |
The content. The head is read for most formats; an Office file is opened. |
fallback |
string? |
null |
What to answer for bytes the library cannot name; "" when null. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of the fallback, when the bytes are missing or cannot be named. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The content is a format the library knows | Its media type, lowercase | The type |
| No bytes, or a format the library does not know | "", or the fallback |
Throws CkFileException |
Read from the bytes themselves: the signature every binary format opens with — %PDF-,
the PNG and JPEG marks, RIFF for webp and wav, the ftyp box of mp4, mov, m4a, heic and
avif, the Matroska header of webm and mkv, ID3 or a frame sync for mp3, OggS, fLaC,
{\rtf, the archive and font marks — and, for the Office formats, one step more: docx,
xlsx, pptx and the OpenDocument three are zip archives told apart by their entries, doc,
xls and ppt compound files told apart by their directory. Text with no signature — no
control character, in UTF-8 or in a mostly-ASCII single-byte encoding such as
Windows-1252, which a spreadsheet writes its CSV in — is text/plain, or
application/json, application/xml, text/html or image/svg+xml when it reads as
one, the marks of a page sought in the whole of it. Never a guess: bytes the library
cannot name answer the fallback. The reader behind the content check of Write,
Copy and Move.
CkFile.SniffType(bytes); // -> "application/pdf" for a PDF, whether it was called scan.pdf or scan.jpg
CkFile.SniffType(bytes); // -> "image/png", "text/plain", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
CkFile.SniffType(bytes, fallback: "application/octet-stream"); // -> the fallback for bytes it cannot name
IsOfType
Whether bytes are what a type says.
bool IsOfType(
byte[]? bytes = null,
string? type = null
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
bytes |
byte[]? |
null |
The content. |
type |
string? |
null |
An extension, "pdf", or a media type, "application/pdf". |
Returns true when the content proves the type, judged by the bytes alone as
SniffType reads them: a PNG is "png" and "image/png" whatever the file was
called, and plain text is any text type — "txt", "csv", "md" — but not HTML, JSON or
XML, which have a look of their own. A type the library does not know, or empty bytes,
answer false. Never throws.
CkFile.IsOfType(bytes, "pdf"); // -> true for a PDF
CkFile.IsOfType(bytes, "image/jpeg"); // -> true for a JPEG
CkFile.IsOfType(pngBytes, "jpg"); // -> false
CkFile.IsOfType(textBytes, "csv"); // -> true (text is text)
ExtensionFor
The extension for a media type.
string ExtensionFor(
string? mediaType = null,
string? fallback = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
mediaType |
string? |
null |
The media type; a parameter after a semicolon is ignored. |
fallback |
string? |
null |
What to answer for a type the library does not know; "" when null. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of the fallback, when the type is missing or unknown. |
Returns the extension, lowercase, without a dot — the reverse of MediaType,
for naming a file that arrived with a Content-Type and no name. The usual one where
several share a type: "jpg", not "jpeg"; "tif"; "html".
CkFile.ExtensionFor("image/jpeg"); // -> "jpg"
CkFile.ExtensionFor("Text/Plain; charset=utf-8"); // -> "txt"
CkFile.ExtensionFor("application/x-whatever"); // -> ""
UniqueName
A file name made unique.
string UniqueName(
string? input = null,
bool throwIfInvalid = CkSettings.DefaultThrowIfInvalid
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The file name as received. |
throwIfInvalid |
bool |
CkSettings.DefaultThrowIfInvalid (false) |
Pass true to throw a CkFileException that says why, instead of answering "", when no name can be made. |
Returns the name as FileName cleans it, with a short random mark before
the extension, so two uploads called the same never overwrite each other and a stored
name cannot be guessed from the original. The extension is kept; a long name is cut to
make room. Different on every call; "" when no name can be made.
CkFile.UniqueName("scan.pdf"); // -> "scan-3f9a1c7e.pdf"
CkFile.UniqueName("my report: final?.docx"); // -> "my report_ final_-b07e2d41.docx"
Explain
Why not — in words, without an exception.
string Explain(
string? input = null,
string? what = nameof(RelativePath)
)
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
string? |
null |
The raw value. |
what |
string? |
nameof(RelativePath) |
The reader to judge by: FileName, Extension, RelativePath, FromBase64 or DataUriType, case-insensitive. |
Returns
| When | You get |
|---|---|
| The value passes the reader | "" |
| It does not | The reason, the same words the exception would carry — an answer, not a failure; it never throws |
The form-friendly twin of throwIfInvalid: the message to show beside the field,
without a try and catch. Every class with a reader has one, on the reader's own
rules, so the reason is exactly what the reader would say. This class has several readers, so what names the one to judge by; a name that is no reader answers a note saying so.
CkFile.Explain("a/../secrets.txt"); // -> the gate's reason
CkFile.Explain("AAAAA", nameof(CkFile.FromBase64)); // -> "not valid base64"
The fallback
FileName, Extension and RelativePath take a fallback — a spare value used when
the input is rejected. The fallback goes through the exact same processing; a bad
fallback answers "" too. FromBase64, DataUriType, HasExtension and the
validators take no fallback — the validators' answer is false.
CkFile.FileName(
input: upload.ClientFileName,
fallback: "upload.bin"
); // -> the cleaned name, or "upload.bin" when nothing usable survives
Good to know
- Sanitizer vs gate.
FileNamerepairs ("who?.pdf"comes back as"who_.pdf");RelativePathrejects (a hostile path "fixed" is still hostile intent). Pick by what the value claims to be: a name, or a path. - Reserved names stay defused, even after truncation. Cutting an over-long name can
expose a reserved name the first check never saw;
FileNamechecks again after the cut, soCONand friends never slip through. RelativePathrejects three ways out: rooted paths, drive or stream colons, and".."climbs. Any one of them rejects the whole value.FromBase64is generous about the text, strict about the verdict. Plain, URL-safe or unpadded base64 and data URIs all decode; whitespace is ignored; input is capped atCkSettings.MaxBase64InputLengthcharacters (about twelve megabytes of file). An empty array always means rejected.DataUriTypeis shape-checked, not verified. A malformed type answers"", but a well-shaped lie ("image/png"on a ZIP file) passes — check the bytes when it matters.- The upload trio. For a data URI upload, run
IsDataUri(well-formed, with a payload),InMediaTypes(a type you accept) andIsWithinSize(small enough), thenFromBase64for the bytes. The first three are cheap and never decode. IsSafeFileNamerejects whereFileNamerepairs. Same rules, opposite policy: use the validator when a client must send a clean name, the sanitizer when you will clean it yourself.- Non-empty in, empty out means rejected. The standard CommonKit signal for the
string methods — check for
""where it matters. To pull a file name out of a payload first, see CkDictionary. - Serve a place's folder with care. A download through Read or a stream over
FullPath sends the type
MediaTypenames. A folder served directly as static files sends whatever the server maps for each extension, and nothing for one it does not know; keep such a folder to the default lists, whose every extension has a type. - Every file operation is inside a place. There is no root, no full path in, and no way to reach a folder the application has not named; FullPath is how a path leaves the library for a stream or a framework's own storage.
- The content check is what makes an upload safe, not the name.
invoice.pdf.exefails on its extension,shell.phprenamedscan.pdfon its content. An extension the library has no type for — one you listed yourself — cannot be checked and passes on your word; every default list holds only extensions the library can prove. Write,CopyandMovenever leave half a file. The bytes go to a dotfile beside the destination,.partial-and sixteen random characters, and are renamed into place at the end, one step on the same volume — a move across two volumes copies to that dotfile too, never to the final name. A write that fails leaves nothing behind, and Files never lists the dotfile.- Large files are streamed, never read.
Readrefuses a file over the place's limit, and the limit is small on purpose; a video is served withFile.OpenReadover FullPath. Deleteanswers true for a file that was never there. The question it answers is "is it gone", so a clean-up needs noExistsfirst.UniqueNameis random by design. Two calls never agree; use it once, when the file is stored, and keep the name.
Taking an upload
An upload is bytes with a name and a claim about what they are, and all three come from
the client. The library's part: clean the name, make it unique, and let the place judge
the file — extension, size and content — before a byte is written. Here it is for a form
upload, in an ASP.NET Core controller, with the folder and the limit set once in
appsettings.json:
{
"CommonKit": {
"Files": {
"Documents": { "Root": "D:\\Files\\Documents", "MaxBytes": 10485760, "Extensions": ["pdf", "csv"] }
}
}
}
using SafeCoder.CommonKit;
using SafeCoder.CommonKit.Enums;
using SafeCoder.CommonKit.Exceptions;
[HttpPost("claims/{claimId}/documents")]
public async Task<IActionResult> Upload(int claimId, IFormFile file)
{
// the bytes: IFormFile is the framework's, so the handler reads it and the library judges it
using MemoryStream buffer = new();
await file.CopyToAsync(buffer);
byte[] bytes = buffer.ToArray();
// the stored name: cleaned, made unique, with the extension the client claimed — the content will have to prove it
string name = CkFile.UniqueName(file.FileName); // "scan-3f9a1c7e.pdf"
string path = "claim-" + CkText.NumberToString(claimId) + "/" + name; // "claim-18/scan-3f9a1c7e.pdf"
try
{
CkFile.Write(FilePlace.Documents, path, bytes, throwIfInvalid: true);
}
catch (CkFileException refused)
{
// "a blocked extension (php, a script the web server runs)", "over 10485760 bytes",
// "the content is text/plain, not a pdf file", "an extension Documents does not take (docx)"
return BadRequest(refused.Reason);
}
return Ok(new { path, size = CkFile.SizeToString(bytes.Length) });
}
That is the whole gate. The client's name never touches the disk, the file never lands
outside the Documents folder, nothing over the limit is kept, and a PDF is a PDF because
its bytes say so. Without throwIfInvalid, the same call answers false and
IsAllowed is the check to run first when the handler needs no reason.
A CSV is data as well as a file. Once it is on disk — or instead of storing it — it goes through the pipeline like any other payload:
if (CkFile.IsOfType(bytes, "csv"))
{
foreach (Dictionary<string, object?> row in CkPayload.FromCsvMaps(Encoding.UTF8.GetString(bytes)))
{
string email = CkEmail.Address(CkDictionary.String(row, "email"));
decimal amount = CkMoney.Amount(CkDictionary.String(row, "amount"), "USD");
// ...
}
}
The same file inside a JSON body travels as base64, and the pipeline is the usual one: CkPayload gets it off the wire, CkDictionary out of the bag, this class onto the disk:
// { "fileName": "scan.pdf", "contentType": "application/pdf", "content": "JVBERi0xLjcK..." }
Dictionary<string, object?> bag = CkPayload.FromJson(body);
byte[] bytes = CkFile.FromBase64(CkDictionary.String(bag, "content")); // plain base64 or a data URI
string fileName = CkDictionary.String(bag, "fileName");
if (CkFile.Extension(fileName).Length == 0) // no usable name: name it by its declared type
{
fileName = "upload." + CkFile.ExtensionFor(CkDictionary.String(bag, "contentType"), fallback: "bin");
}
CkFile.Write(FilePlace.Documents, "claim-18/" + CkFile.UniqueName(fileName), bytes, throwIfInvalid: true);
Serving it back is the reverse. A small file is its bytes; a large one is a stream over FullPath, which never loads it:
[HttpGet("claims/{claimId}/documents/{name}")]
public IActionResult Download(int claimId, string name)
{
string path = "claim-" + CkText.NumberToString(claimId) + "/" + CkFile.FileName(name);
if (CkFile.Exists(FilePlace.Documents, path) == false)
{
return NotFound();
}
return File(
System.IO.File.OpenRead(CkFile.FullPath(FilePlace.Documents, path)),
CkFile.MediaType(path),
name
);
}
If you want errors instead
Pass throwIfInvalid: true and a value that cannot be used raises a
CkFileException (from SafeCoder.CommonKit.Exceptions) instead of answering empty. The
exception carries the Input, what was Expected and a short Reason, flattened into
a one-line message. The exceptions to the rule take no throwIfInvalid: HasExtension
and InMediaTypes, whose allow-list must be the last parameter — call Extension or
DataUriType with it first when you need the error — and the validators and readers of the
places, which answer false, null or empty by nature: Exists, IsAllowed, IsOfType,
ReadOrNull, SizeOrNull, Files, AllowedExtensions, BlockedExtensions and MaxBytes.
CkFile.RelativePath(
input: "a/../secrets.txt",
throwIfInvalid: true
); // throws CkFileException — the message says why
One thing to know when a file operation throws: the Reason names the kind of failure
and never a server path, but the exception's InnerException, when the operating system
refused, carries the system's own message with the full path in it. Show a client the
Reason, never ToString().