diff options
Diffstat (limited to 'Emby.Server.Implementations/AppBase/ConfigurationHelper.cs')
| -rw-r--r-- | Emby.Server.Implementations/AppBase/ConfigurationHelper.cs | 36 |
1 files changed, 20 insertions, 16 deletions
diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index 90b97061f..3a916e5c0 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -6,13 +6,13 @@ using MediaBrowser.Model.Serialization; namespace Emby.Server.Implementations.AppBase { /// <summary> - /// Class ConfigurationHelper + /// Class ConfigurationHelper. /// </summary> public static class ConfigurationHelper { /// <summary> /// Reads an xml configuration file from the file system - /// It will immediately re-serialize and save if new serialization data is available due to property changes + /// It will immediately re-serialize and save if new serialization data is available due to property changes. /// </summary> /// <param name="type">The type.</param> /// <param name="path">The path.</param> @@ -22,7 +22,7 @@ namespace Emby.Server.Implementations.AppBase { object configuration; - byte[] buffer = null; + byte[]? buffer = null; // Use try/catch to avoid the extra file system lookup using File.Exists try @@ -33,27 +33,31 @@ namespace Emby.Server.Implementations.AppBase } catch (Exception) { - configuration = Activator.CreateInstance(type); + // Note: CreateInstance returns null for Nullable<T>, e.g. CreateInstance(typeof(int?)) returns null. + configuration = Activator.CreateInstance(type)!; } - using (var stream = new MemoryStream()) + using var stream = new MemoryStream(buffer?.Length ?? 0); + xmlSerializer.SerializeToStream(configuration, stream); + + // Take the object we just got and serialize it back to bytes + Span<byte> newBytes = stream.GetBuffer().AsSpan(0, (int)stream.Length); + + // If the file didn't exist before, or if something has changed, re-save + if (buffer == null || !newBytes.SequenceEqual(buffer)) { - xmlSerializer.SerializeToStream(configuration, stream); + var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path)); - // Take the object we just got and serialize it back to bytes - var newBytes = stream.ToArray(); + Directory.CreateDirectory(directory); - // If the file didn't exist before, or if something has changed, re-save - if (buffer == null || !buffer.SequenceEqual(newBytes)) + // Save it after load in case we got new items + using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { - Directory.CreateDirectory(Path.GetDirectoryName(path)); - - // Save it after load in case we got new items - File.WriteAllBytes(path, newBytes); + fs.Write(newBytes); } - - return configuration; } + + return configuration; } } } |
