Framework/Core/SafeDataFile.cs

Static helper that wraps FileSystem.Data for text files in the data folder. Writes go to a ".tmp" copy first, then overwrite the real file, and Read falls back to the temp copy when the main file fails a caller-supplied validity check.

using System;

namespace RoleplayFramework.Core;

/// <summary>
/// Crash-tolerant text files in the data folder. s&amp;box exposes no public rename/atomic write, so a write first
/// stores the new content in "&lt;path&gt;.tmp", then overwrites the real file, then removes the temp copy.
/// If the process dies mid-write, <see cref="Read"/> falls back to the temp copy when the main file fails validation.
/// </summary>
public static class SafeDataFile
{
	static BaseFileSystem Fs => FileSystem.Data;

	public static void Write( string path, string text )
	{
		int slash = path.LastIndexOf( '/' );
		if ( slash > 0 )
		{
			var dir = path.Substring( 0, slash );
			if ( !Fs.DirectoryExists( dir ) ) Fs.CreateDirectory( dir );
		}

		var tmp = path + ".tmp";
		Fs.WriteAllText( tmp, text );
		Fs.WriteAllText( path, text );
		Fs.DeleteFile( tmp );
	}

	/// <summary>
	/// Returns the main file's text if <paramref name="isValid"/> accepts it, otherwise the temp copy's
	/// (recovering an interrupted write), otherwise null. <paramref name="recoveredFromTemp"/> reports which.
	/// </summary>
	public static string Read( string path, Func<string, bool> isValid, out bool recoveredFromTemp )
	{
		recoveredFromTemp = false;

		if ( Fs.FileExists( path ) )
		{
			var text = Fs.ReadAllText( path );
			if ( isValid( text ) ) return text;
		}

		var tmp = path + ".tmp";
		if ( Fs.FileExists( tmp ) )
		{
			var text = Fs.ReadAllText( tmp );
			if ( isValid( text ) )
			{
				recoveredFromTemp = true;
				return text;
			}
		}

		return null;
	}

	public static bool Exists( string path ) => Fs.FileExists( path ) || Fs.FileExists( path + ".tmp" );
}