ConfigurationHelper.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 (Exception)
  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. Directory.CreateDirectory(Path.GetDirectoryName(path));
  40. // Save it after load in case we got new items
  41. File.WriteAllBytes(path, newBytes);
  42. }
  43. return configuration;
  44. }
  45. /// <summary>
  46. /// Reads an xml configuration file from the file system
  47. /// It will immediately save the configuration after loading it, just
  48. /// in case there are new serializable properties
  49. /// </summary>
  50. /// <typeparam name="T"></typeparam>
  51. /// <param name="path">The path.</param>
  52. /// <param name="xmlSerializer">The XML serializer.</param>
  53. /// <returns>``0.</returns>
  54. public static T GetXmlConfiguration<T>(string path, IXmlSerializer xmlSerializer)
  55. where T : class
  56. {
  57. return GetXmlConfiguration(typeof(T), path, xmlSerializer) as T;
  58. }
  59. }
  60. }