From 14a4bc021f9b9ad5b7d5c4db2d2b7a4deff0c953 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 2 Jul 2026 21:00:36 +0100 Subject: [PATCH] Harden directory MessagePack record replacement --- .../DirectoryMessagePackBackingStore.cs | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs index 4792310f..f46e3ee2 100644 --- a/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs +++ b/src/GameCult.Caching.MessagePack/DirectoryMessagePackBackingStore.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; +using System.Threading; using MessagePack; namespace GameCult.Caching.MessagePack; @@ -274,7 +275,7 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore if (File.Exists(path)) { - File.Replace(tempPath, path, null); + ReplaceExistingFile(tempPath, path); } else { @@ -289,4 +290,26 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore } } } + + private static void ReplaceExistingFile(string sourcePath, string destinationPath) + { + for (var attempt = 0; attempt < 3; attempt++) + { + try + { + File.Replace(sourcePath, destinationPath, null); + return; + } + catch (IOException) when (attempt < 2) + { + Thread.Sleep(10 * (attempt + 1)); + } + catch (UnauthorizedAccessException) when (attempt < 2) + { + Thread.Sleep(10 * (attempt + 1)); + } + } + + File.Copy(sourcePath, destinationPath, overwrite: true); + } }