From magazine topic to project implementation
Relevant service and technical pages for this post
The moment is inconspicuous: a service shuts down, an auto-updater swaps files, the Task Manager gets one click too many — and of all times an INI is being saved. On the next start there is no „Config missing“ dialog, but a real operational problem: the service won’t start, the interface remains down, the ticket lands with the wrong team, and in the end someone finds a 0-Byte INI in the program directory.
When you face the decision to implement Delphi: INI/Config atomar aktualisieren, it is rarely about „Clean Code“. It is a conflict of objectives: as little I/O and error-path logic as possible versus reliable behavior on crash, kill or power loss. Those who write configuration for production-like environments (Windows- and Linux-Services, terminal servers, kiosks, scheduled jobs) often cannot afford the naive variant.
This article follows a decision path: which options exist, what they actually do in failure cases, which Windows mechanisms lie behind them (Write-through, Flush, atomic Replace) and which first step immediately gives you operational reliability — without turning an INI into a major project.
Delphi: INI/Config atomic updates in practice
Before you compare APIs, clarify the risk class. This is not an academic exercise; it determines how much „crash safety“ you actually need to procure.
- Non-critical: window positions, recently opened lists, UI layout. Reset is acceptable.
- Relevant: endpoints, paths, feature toggles, tenant/license parameters. Errors generate support effort and lost time.
- Critical: service start parameters, job control, security-relevant switches. Errors can cause downtime or disable protection measures.
From „relevant“ onward an atomic replace is generally a well-spent effort. From „critical“ you should assume that a robust storage pattern is mandatory – plus tests that actually hit the kill point.
Options in comparison: What really happens on crash?
The typical trap: you evaluate options by „how often does it work“ instead of „how broken is it if it fails“. The following matrix is therefore intentionally written from an operational perspective.
| Option | Implementation effort | Behavior on crash/kill | Common pitfalls | Suitable when … |
|---|---|---|---|---|
| Write directly into the target file | low | Risk: partial content, 0 bytes, invalid format | Abort in the middle of the write; competing scanners/indexers | Config is disposable and not start-critical |
| Write temp file, then Rename/Move | medium | Mostly consistent, but not necessarily „durable“ without flush | Temp on another volume; copy+delete instead of rename; metadata in cache | You want atomicity but not maximal persistence guarantee |
| Temp + Flush + ReplaceFile (atomic replace) | medium | Very robust: old or new file, rarely „in between“ | Sharing violations, permissions/ACLs, volume rule, backup path | Config is relevant/critical or you operate services/kiosk |
| Journal/transaction format (append + commit) | high | Maximum control (replay/rollback possible) | More tests, migration, tooling, log rotation | Many writes, multiple writers, or auditable changes required |
The core conflict: atomicity is not the same as persistence
Many teams stop at „temp file + rename“—understandable, since it prevents direct overwrites. But crash safety has two levels:
- Atomicity: Readers should see either the old or the new version, not an intermediate state.
- Persistence („durable write“): After a power loss the new version must really be on the storage device — not just in the cache.
Windows typically buffers write operations in the system cache. Without an explicit flush the cache algorithm decides when data reaches the storage device.[Source] Practical implication: A pattern can appear „logically clean“ and still end badly on power loss if you neither use write-through nor flush.
In many enterprise applications atomicity is the bigger lever (no broken INI). Persistence becomes critical where devices are hard-powered off, in embedded/industrial environments, or where configuration changes are rare but extremely costly when they fail.
The robust path: temp file, write-through/flush, then atomic replace
If you opt for „robust“, your storage pattern should be clear and verifiable. Not a magic utility, but the result of verifiable steps:
- Create a temp file in the target folder (or at least guaranteed on the same volume). This is the prerequisite so that a Replace is truly a Replace — and not Copy+Delete.
- Write completely to the temp file (including encoding decision; close the file so buffers move into the I/O stack).
- Trigger persistence: open the file handle with
FILE_FLAG_WRITE_THROUGHand/or callFlushFileBuffers. Microsoft describes write-through as writing „without delay“ from the cache; for metadata and end-to-end durability the CreateFile documentation still refers to FlushFileBuffers.[Source] - Replace atomically: use
ReplaceFileW(optionally with backup). This encapsulates the swap as a single operation and is built for this purpose. - Make error paths visible: What happens on Sharing-Violation, on insufficient rights, on missing target file? Log the step and the error code.
One detail is non-negotiable: ReplaceFileW requires that the replaced file and the replacement file reside on the same volume.[Source] That is precisely why „Temp in %TEMP%“ is a dangerous default: in Roaming/VDI scenarios or with redirected profiles the volume can vary, and your „atomic“ step suddenly is no longer atomic.
Delphi INI classes correctly categorized: UpdateFile is not your crash-safety anchor
TIniFile and TMemIniFile are convenient and in many projects entirely sufficient. The difference is roughly: TMemIniFile collects changes in memory and writes them bundled; TIniFile works closer to the file (depending on implementation/version). For crash safety, however, what „Update“ ultimately means is decisive.
The RAD Studio documentation for System.IniFiles.TIniFile.UpdateFile describes writing buffered data but relativizes the effect historically (under NT it may have „no effect“).[Source] Practical consequence: UpdateFile is useful for the „getting out of Delphi buffering“ problem, but not the final step for crash- or power-loss scenarios.
If your configuration is business-critical, treat INI writes like any other persistent change: you need a pattern that is correct at the file-handle and filesystem level.
ReplaceFileW or MoveFileEx? Decide according to semantics
Both approaches can „replace“, but the semantics are not identical. These nuances determine whether your support later sees „sporadically broken“ or a „clear error code“.
ReplaceFileW: replacement with optional backup
ReplaceFileW is tailored to the use case „replace target file with replacement file.“ You can optionally have a backup file created and in many cases preserve attributes of the target object. For configuration this is often suitable, because a backup enables the fastest rollback in case of error — even without a debugger.
MoveFileEx: general rename/move, with flags
MoveFileEx with MOVEFILE_REPLACE_EXISTING can also replace. In common headers there is also MOVEFILE_WRITE_THROUGH to treat the move/replace step write-through. The catch is less „cannot“ and more „you must compose your desired semantics yourself“ (backup, attributes, error handling, tests).
For an INI that influences service start, ReplaceFileW is often the clearer fit. For very simple cases MoveFileEx can suffice — but then you should consciously accept and test the consequences (no backup, different semantics).
Pitfalls that in practice really generate tickets
Temp file in the wrong directory (and suddenly it’s Copy+Delete)
If the temp file and the target are not on the same volume, the replacement cannot be atomic. This is particularly insidious because it „always worked“ on developer machines and only breaks in customer environments (redirected profiles, different drive mappings, App-V/VDI).
AV/Indexer/Backup agents keep the target briefly open
Configuration files are often scanned or indexed. Then Replace sporadically fails with a sharing violation. This is not a reason to discard the pattern — but it is a reason to log error codes and implement a short, bounded retry with backoff (e.g. a few attempts within a few hundred milliseconds). Important: retries must not block shutdown/service stop.
ACLs and ownership: permissions don’t match after Replace
If the original file was created by the installer with specific ACLs, a newly created file may carry different permissions. ReplaceFile can preserve attributes, but that’s no excuse for not verifying. For operation the only thing that counts in the end is: can the Service-Identity read and write after the update? Plan for this test case, especially for Program Files vs. ProgramData.
Multiple writers: atomically replaced, but logically lost
Atomic Replace prevents „partially written“, not „overwritten“. If two processes perform „read → modify → write“, the last one wins. If you truly have two writers (Service + Admin-Tool), you need coordination: mutex, lock file, or a central component that serializes writes. Otherwise you only solve one problem and create another.
Debugging approach: making the crash edge case reproducible
Crash safety cannot be „believed“; it must be provoked. A practical test is not elegant, but unambiguous.
- Stress writes: Save in rapid succession and vary length/content so different write patterns occur.
- Hard kill: Terminate the process forcefully during the save (e.g. taskkill /F). Not „Close“, not „Exit“.
- Validate after each restart: File must not be 0 bytes, must be parseable, required keys must exist.
- Stepwise logging: Don’t log „Save OK“, but: temp created, temp written, flush OK/error code, replace OK/error code, backup yes/no.
- Vary environment: SSD/HDD, VM with hard poweroff, terminal server profile, network share (if relevant).
If later you only see „Settings saved“ in the logs, that helps no one. If, however, you see „Replace failed: Sharing violation“, the next measure is clear: adjust the retry window, check the path/scanner, evaluate locking concepts.
When robust code isn’t justified — and what still remains mandatory
There are projects where a complete replace/flush path is disproportionate: single-user tool, configuration purely cosmetic, writes are rare, and a reset is acceptable. Then „normal save“ can be defensible.
Two things you should not omit even then:
- Recovery during loading: If the INI is not parseable, do not abort abruptly. Set defaults, optionally back up the corrupt file and rewrite it.
- Minimal validation: Check required sections and required keys so that “half-plausible” input does not lead to follow-on errors that are later misinterpreted as network or database problems.
This is the actual efficiency lever: you prevent a broken text file from becoming an operational incident—regardless of whether you have already implemented the most robust write path.
First step: Short checklist for the team’s decision
- Can the process be terminated hard during save? (service shutdown, update, kiosk) If yes: plan a Replace-Pattern.
- Is the configuration critical for startup? If yes: replace atomically and provide a backup option.
- Is the file actually local on NTFS? If not: testing effort increases, but the pattern remains sensible.
- Are there multiple writers? If yes: additionally design locking/serialization.
- Are error paths visible? If not: add step-level logging first.
If you answer “yes” to two or more points, the likelihood is high that an atomic replace will save you tickets that otherwise occur only sporadically—and are therefore particularly costly.
Closing point: Atomic updates require consideration of operations
INI files are small, but their impact often is not. A robust pattern for „Delphi: INI/Config atomically update“ is not a luxury: temp file in the target folder, flush/write-through where it counts, and an atomic swap (typically ReplaceFileW) plus traceable error paths. That way you not only have an intact file in the critical case, but also an answer to the support question “What exactly happened?”
If you want to apply the pattern cleanly across the estate (including test strategy, locking concept and a migration path for multiple config locations), this can be clarified most quickly in a short technical alignment: get in touch.
Sources and further information
The technical core statements were editorially contextualized based on the following external sources.
- Flushing System-Buffered I/O Data to Disk – Win32 apps | Microsoft Learn (learn.microsoft.com)
Windows buffers file writes; without an explicit flush, cache algorithms determine when data actually reach the storage medium, which is why FlushFileBuffers is relevant for durable writes. - CreateFileA function (fileapi.h) – Win32 apps | Microsoft Learn (learn.microsoft.com)
FILE_FLAG_WRITE_THROUGH describes write-through behavior for CreateFile; for metadata durability FlushFileBuffers is still referenced. - ReplaceFileW function (winbase.h) – Win32 apps | Microsoft Learn (learn.microsoft.com)
ReplaceFileW encapsulates replacing a file and assumes that the file being replaced and the replacement file reside on the same volume. - System.IniFiles.TIniFile.UpdateFile – RAD Studio API Documentation (docwiki.embarcadero.com)
TIniFile.UpdateFile is documented as flushing buffered changes and is historically/contextually qualified for NT systems.
For this topic, Atomic file replacement and Replacefilew Delphi are also important. The article contextualizes these aspects and shows what matters in day-to-day operations.
Discuss a project or modernization initiative with Net-Base.
Next step
When the topic becomes an actual project, architecture, existing systems and operations should be considered together from the outset.
We support not only with individual issues, but also when source snippets, legacy topics, or portal ideas are to be turned into a robust enterprise project.
- Current state, target state and technical risks are assessed jointly.
- REST, data access, portals and rollout are not deferred to a later stage as secondary consequences.
- You can see early on which path is economically and operationally viable.