diff --git a/src/MonkeyCache.FileStore/Barrel.cs b/src/MonkeyCache.FileStore/Barrel.cs index f2cc6ec..f65313d 100644 --- a/src/MonkeyCache.FileStore/Barrel.cs +++ b/src/MonkeyCache.FileStore/Barrel.cs @@ -285,7 +285,7 @@ public IEnumerable GetKeys(CacheState state = CacheState.Active) } } - T Get(string key, Func deserialize) + T Get(string key, Func deserialize) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Key can not be null or empty.", nameof(key)); @@ -301,14 +301,13 @@ T Get(string key, Func deserialize) if (index.ContainsKey(key) && File.Exists(path) && (!AutoExpire || (AutoExpire && !IsExpired(key)))) { - var contents = File.ReadAllText(path); if (BarrelUtils.IsString(result)) { - object final = contents; - return (T)final; + return (T)(object)File.ReadAllText(path); } - result = deserialize(contents); + using FileStream fileStream = new(path, FileMode.Open, FileAccess.Read); + result = deserialize(fileStream); } } finally @@ -322,15 +321,15 @@ T Get(string key, Func deserialize) /// [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo, or make sure all of the required types are preserved.")] public T Get(string key, JsonSerializerOptions options = null) => - Get(key, contents => JsonDeserialize(contents, options)); + Get(key, fileStream => JsonDeserialize(fileStream, options)); [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Workaround https://github.com/dotnet/linker/issues/2001")] - static T JsonDeserialize(string contents, JsonSerializerOptions options) => - JsonSerializer.Deserialize(contents, options); + static T JsonDeserialize(FileStream fileStream, JsonSerializerOptions options) => + JsonSerializer.Deserialize(fileStream, options); /// - public T Get(string key, JsonTypeInfo jsonTypeInfo) => Get(key, contents => - JsonSerializer.Deserialize(contents, jsonTypeInfo)); + public T Get(string key, JsonTypeInfo jsonTypeInfo) => Get(key, fileStream => + JsonSerializer.Deserialize(fileStream, jsonTypeInfo)); /// /// Gets the DateTime that the item will expire for the specified key.