| | 1 | | using System; |
| | 2 | | using System.IO; |
| | 3 | | using MediaBrowser.Model.Serialization; |
| | 4 | |
|
| | 5 | | namespace Emby.Server.Implementations.AppBase |
| | 6 | | { |
| | 7 | | /// <summary> |
| | 8 | | /// Class ConfigurationHelper. |
| | 9 | | /// </summary> |
| | 10 | | public static class ConfigurationHelper |
| | 11 | | { |
| | 12 | | /// <summary> |
| | 13 | | /// Reads an xml configuration file from the file system |
| | 14 | | /// It will immediately re-serialize and save if new serialization data is available due to property changes. |
| | 15 | | /// </summary> |
| | 16 | | /// <param name="type">The type.</param> |
| | 17 | | /// <param name="path">The path.</param> |
| | 18 | | /// <param name="xmlSerializer">The XML serializer.</param> |
| | 19 | | /// <returns>System.Object.</returns> |
| | 20 | | public static object GetXmlConfiguration(Type type, string path, IXmlSerializer xmlSerializer) |
| | 21 | | { |
| | 22 | | object configuration; |
| | 23 | |
|
| 21 | 24 | | byte[]? buffer = null; |
| | 25 | |
|
| | 26 | | // Use try/catch to avoid the extra file system lookup using File.Exists |
| | 27 | | try |
| | 28 | | { |
| 21 | 29 | | buffer = File.ReadAllBytes(path); |
| | 30 | |
|
| 0 | 31 | | configuration = xmlSerializer.DeserializeFromBytes(type, buffer); |
| 0 | 32 | | } |
| 21 | 33 | | catch (Exception) |
| | 34 | | { |
| | 35 | | // Note: CreateInstance returns null for Nullable<T>, e.g. CreateInstance(typeof(int?)) returns null. |
| 21 | 36 | | configuration = Activator.CreateInstance(type)!; |
| 21 | 37 | | } |
| | 38 | |
|
| 21 | 39 | | using var stream = new MemoryStream(buffer?.Length ?? 0); |
| 21 | 40 | | xmlSerializer.SerializeToStream(configuration, stream); |
| | 41 | |
|
| | 42 | | // Take the object we just got and serialize it back to bytes |
| 21 | 43 | | Span<byte> newBytes = stream.GetBuffer().AsSpan(0, (int)stream.Length); |
| | 44 | |
|
| | 45 | | // If the file didn't exist before, or if something has changed, re-save |
| 21 | 46 | | if (buffer is null || !newBytes.SequenceEqual(buffer)) |
| | 47 | | { |
| 21 | 48 | | var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is n |
| | 49 | |
|
| 21 | 50 | | Directory.CreateDirectory(directory); |
| | 51 | |
|
| | 52 | | // Save it after load in case we got new items |
| 21 | 53 | | using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) |
| | 54 | | { |
| 21 | 55 | | fs.Write(newBytes); |
| 21 | 56 | | } |
| | 57 | | } |
| | 58 | |
|
| 21 | 59 | | return configuration; |
| 21 | 60 | | } |
| | 61 | | } |
| | 62 | | } |