ConfigurationHelper.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using MediaBrowser.Model.Serialization;
  2. using System;
  3. using System.IO;
  4. using System.Linq;
  5. namespace MediaBrowser.Common.Configuration
  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 (FileNotFoundException)
  31. {
  32. configuration = Activator.CreateInstance(type);
  33. }
  34. // Take the object we just got and serialize it back to bytes
  35. var newBytes = xmlSerializer.SerializeToBytes(configuration);
  36. // If the file didn't exist before, or if something has changed, re-save
  37. if (buffer == null || !buffer.SequenceEqual(newBytes))
  38. {
  39. // Save it after load in case we got new items
  40. File.WriteAllBytes(path, newBytes);
  41. }
  42. return configuration;
  43. }
  44. /// <summary>
  45. /// Reads an xml configuration file from the file system
  46. /// It will immediately save the configuration after loading it, just
  47. /// in case there are new serializable properties
  48. /// </summary>
  49. /// <typeparam name="T"></typeparam>
  50. /// <param name="path">The path.</param>
  51. /// <param name="xmlSerializer">The XML serializer.</param>
  52. /// <returns>``0.</returns>
  53. public static T GetXmlConfiguration<T>(string path, IXmlSerializer xmlSerializer)
  54. where T : class
  55. {
  56. return GetXmlConfiguration(typeof(T), path, xmlSerializer) as T;
  57. }
  58. }
  59. }