ConfigurationHelper.cs 2.5 KB

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