Boost Your .NET Projects with Spargine: Atomic File Writes and Fallback Reads

Saving a settings file sounds simple until a write is interrupted halfway through and leaves the file incomplete. Reading that file presents a different problem. If it’s missing or inaccessible, can your application keep running with sensible defaults?

Spargine’s FileInfoExtensions gives you a way to handle both cases directly from a FileInfo instance. Write the new contents to a temporary file before moving them into place or supply fallback text for reads that can fail without stopping the application. These methods are available in the DotNetTips.Spargine.Extensions project and NuGet package, and all three use UTF-8 by default.

Methods

ReadAllTextSafe(string fallback = “”, Encoding? encoding = null)

This method reads the entire file and returns the supplied fallback if the file is missing or if the read throws an IOException or UnauthorizedAccessException. The fallback defaults to an empty string. For an optional JSON settings file, you could supply "{}" if an empty object is valid for your application.

There is also an async version of this method.

WriteAllTextAtomic(string content, Encoding? encoding = null)

This is the method I’d reach for when saving a settings file or regenerating a text report. It calls CreateTempFileThenMove internally, so it uses the same temporary-file workflow. The name makes the intent clear at the call site.

There is also an async version of this method.

Summary

Use WriteAllTextAtomic when you want to finish writing the new text before replacing an existing file. For optional files, use ReadAllTextSafe with a fallback your application can actually use. If your application needs to distinguish a missing file from a permissions problem, handle those errors explicitly so you can log or report the cause.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copyrighted and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a Reply