2
0

ConfigurationHelper.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using MediaBrowser.Model.Serialization;
  2. using System;
  3. using System.IO;
  4. using System.Linq;
  5. using MediaBrowser.Model.IO;
  6. namespace MediaBrowser.Common.Implementations.Configuration
  7. {
  8. /// <summary>
  9. /// Class ConfigurationHelper
  10. /// </summary>
  11. public static class ConfigurationHelper
  12. {
  13. /// <summary>
  14. /// Reads an xml configuration file from the file system
  15. /// It will immediately re-serialize and save if new serialization data is available due to property changes
  16. /// </summary>
  17. /// <param name="type">The type.</param>
  18. /// <param name="path">The path.</param>
  19. /// <param name="xmlSerializer">The XML serializer.</param>
  20. /// <returns>System.Object.</returns>
  21. public static object GetXmlConfiguration(Type type, string path, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
  22. {
  23. object configuration;
  24. byte[] buffer = null;
  25. // Use try/catch to avoid the extra file system lookup using File.Exists
  26. try
  27. {
  28. buffer = fileSystem.ReadAllBytes(path);
  29. configuration = xmlSerializer.DeserializeFromBytes(type, buffer);
  30. }
  31. catch (Exception)
  32. {
  33. configuration = Activator.CreateInstance(type);
  34. }
  35. using (var stream = new MemoryStream())
  36. {
  37. xmlSerializer.SerializeToStream(configuration, stream);
  38. // Take the object we just got and serialize it back to bytes
  39. var newBytes = stream.ToArray();
  40. // If the file didn't exist before, or if something has changed, re-save
  41. if (buffer == null || !buffer.SequenceEqual(newBytes))
  42. {
  43. fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  44. // Save it after load in case we got new items
  45. fileSystem.WriteAllBytes(path, newBytes);
  46. }
  47. return configuration;
  48. }
  49. }
  50. }
  51. }