ConfigurationHelper.cs 2.0 KB

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