ConfigurationHelper.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #nullable enable
  2. using System;
  3. using System.IO;
  4. using System.Linq;
  5. using MediaBrowser.Common.Extensions;
  6. using MediaBrowser.Model.Serialization;
  7. namespace Emby.Server.Implementations.AppBase
  8. {
  9. /// <summary>
  10. /// Class ConfigurationHelper.
  11. /// </summary>
  12. public static class ConfigurationHelper
  13. {
  14. /// <summary>
  15. /// Reads an xml configuration file from the file system
  16. /// It will immediately re-serialize and save if new serialization data is available due to property changes.
  17. /// </summary>
  18. /// <param name="type">The type.</param>
  19. /// <param name="path">The path.</param>
  20. /// <param name="xmlSerializer">The XML serializer.</param>
  21. /// <returns>System.Object.</returns>
  22. public static object GetXmlConfiguration(Type type, string path, IXmlSerializer xmlSerializer)
  23. {
  24. object configuration;
  25. byte[]? buffer = null;
  26. // Use try/catch to avoid the extra file system lookup using File.Exists
  27. try
  28. {
  29. buffer = File.ReadAllBytes(path);
  30. configuration = xmlSerializer.DeserializeFromBytes(type, buffer);
  31. }
  32. catch (Exception)
  33. {
  34. configuration = Activator.CreateInstance(type) ?? throw new ArgumentException($"Provided path ({type}) is not valid.", nameof(type));
  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) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path));
  45. Directory.CreateDirectory(directory);
  46. // Save it after load in case we got new items
  47. // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
  48. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
  49. {
  50. fs.Write(newBytes, 0, newBytesLen);
  51. }
  52. }
  53. return configuration;
  54. }
  55. }
  56. }