ConfigurationHelper.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using MediaBrowser.Model.IO;
  5. using MediaBrowser.Model.Serialization;
  6. namespace Emby.Server.Implementations.AppBase
  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. /// <param name="fileSystem">The file system</param>
  21. /// <returns>System.Object.</returns>
  22. public static object GetXmlConfiguration(Type type, string path, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
  23. {
  24. object configuration;
  25. byte[] buffer = null;
  26. // Use try/catch to avoid the extra file system lookup using File.Exists
  27. try
  28. {
  29. buffer = fileSystem.ReadAllBytes(path);
  30. configuration = xmlSerializer.DeserializeFromBytes(type, buffer);
  31. }
  32. catch (Exception)
  33. {
  34. configuration = Activator.CreateInstance(type);
  35. }
  36. using (var stream = new MemoryStream())
  37. {
  38. xmlSerializer.SerializeToStream(configuration, stream);
  39. // Take the object we just got and serialize it back to bytes
  40. var newBytes = stream.ToArray();
  41. // If the file didn't exist before, or if something has changed, re-save
  42. if (buffer == null || !buffer.SequenceEqual(newBytes))
  43. {
  44. fileSystem.CreateDirectory(fileSystem.GetDirectoryName(path));
  45. // Save it after load in case we got new items
  46. fileSystem.WriteAllBytes(path, newBytes);
  47. }
  48. return configuration;
  49. }
  50. }
  51. }
  52. }