ConfigurationHelper.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using MediaBrowser.Model.Serialization;
  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. byte[]? buffer = null;
  24. // Use try/catch to avoid the extra file system lookup using File.Exists
  25. try
  26. {
  27. buffer = File.ReadAllBytes(path);
  28. configuration = xmlSerializer.DeserializeFromBytes(type, buffer);
  29. }
  30. catch (Exception)
  31. {
  32. configuration = Activator.CreateInstance(type) ?? throw new ArgumentException($"Provided path ({type}) is not valid.", nameof(type));
  33. }
  34. using var stream = new MemoryStream(buffer?.Length ?? 0);
  35. xmlSerializer.SerializeToStream(configuration, stream);
  36. // Take the object we just got and serialize it back to bytes
  37. byte[] newBytes = stream.GetBuffer();
  38. int newBytesLen = (int)stream.Length;
  39. // If the file didn't exist before, or if something has changed, re-save
  40. if (buffer == null || !newBytes.AsSpan(0, newBytesLen).SequenceEqual(buffer))
  41. {
  42. var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path));
  43. Directory.CreateDirectory(directory);
  44. // Save it after load in case we got new items
  45. // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
  46. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
  47. {
  48. fs.Write(newBytes, 0, newBytesLen);
  49. }
  50. }
  51. return configuration;
  52. }
  53. }
  54. }