2
0

ConfigurationHelper.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. configuration = Activator.CreateInstance(type);
  34. }
  35. using var stream = new MemoryStream(buffer?.Length ?? 0);
  36. xmlSerializer.SerializeToStream(configuration, stream);
  37. // Take the object we just got and serialize it back to bytes
  38. byte[] newBytes = stream.GetBuffer();
  39. int newBytesLen = (int)stream.Length;
  40. // If the file didn't exist before, or if something has changed, re-save
  41. if (buffer == null || !newBytes.AsSpan(0, newBytesLen).SequenceEqual(buffer))
  42. {
  43. Directory.CreateDirectory(Path.GetDirectoryName(path));
  44. // Save it after load in case we got new items
  45. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
  46. {
  47. fs.Write(newBytes, 0, newBytesLen);
  48. }
  49. }
  50. return configuration;
  51. }
  52. }
  53. }