Class SafeFileWriter
A helper for writing a file in a reliable way.
public static class SafeFileWriter
- Inheritance
-
SafeFileWriter
- Inherited Members
Methods
CreateOrReplace(string, Action<string>)
Creates or replaces a file such that if the writing fails for any reason, a partially-written file will not be produced, with any original existing file preserved.
public static void CreateOrReplace(string path, Action<string> writer)
Parameters
path
stringThe file to write to.
writer
Action<string>The action that writes the file. The single argument is the path to a temporary file in the same directory as
path
that does not initially exist to which the file should be written.
Remarks
The temporary file will be in the same folder and have the same name as path
, with ".tmp" appended.
For example, if path
is "C:\folder\file.txt", then the temporary file will be "C:\folder\file.txt.tmp".
This file will be cleaned up upon exit if possible, but if it can't for any reason, it will silently be left behind.
If the path
file already exists when this is called, a backup file is used to ensure the file is updated properly.
The backup file will be in the same folder and have the same name as path
, with ".bak" appended.
For example, if path
is "C:\folder\file.txt", then the backup file will be "C:\folder\file.txt.bak".
This file will be cleaned up upon exit if possible, but if it can't for any reason, it will silently be left behind.
If the operation completes with no errors, then the file specified by path
will contain the file content written by writer
.
If the operation fails for any reason, then the file specified by path
will reflect its original state before this method is called.
Exceptions
- ArgumentNullException
path
is null.- ArgumentNullException
writer
is null.- IOException
Unable to delete the preexisting temporary file. The inner exception will contain the source error.
- IOException
Unable to delete the preexisting backup file. The inner exception will contain the source error.
- Exception
An exception thrown by
writer
. Note that a file name in the thrown exception will reference a temporary file, notpath
.- InvalidOperationException
writer
did not create the file.- IOException
Unable to rename the temporary file. The inner exception will contain the source error.
- IOException
Unable to replace the file with the temporary file. The inner exception will contain the source error.