ConfigurationHelper.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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);
  33. }
  34. using var stream = new MemoryStream();
  35. xmlSerializer.SerializeToStream(configuration, stream);
  36. // Take the object we just got and serialize it back to bytes
  37. var newBytes = stream.ToArray();
  38. // If the file didn't exist before, or if something has changed, re-save
  39. if (buffer == null || !buffer.SequenceEqual(newBytes))
  40. {
  41. Directory.CreateDirectory(Path.GetDirectoryName(path));
  42. // Save it after load in case we got new items
  43. File.WriteAllBytes(path, newBytes);
  44. }
  45. return configuration;
  46. }
  47. }
  48. }