From 5d55b36487b25b2efaf6923a3c069f4b0b59a449 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 20 Feb 2017 15:50:58 -0500 Subject: make more classes portable --- .../AppBase/ConfigurationHelper.cs | 60 ++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Emby.Server.Implementations/AppBase/ConfigurationHelper.cs (limited to 'Emby.Server.Implementations/AppBase/ConfigurationHelper.cs') diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs new file mode 100644 index 000000000..ad2f45945 --- /dev/null +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using System.Linq; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; + +namespace Emby.Server.Implementations.AppBase +{ + /// + /// Class ConfigurationHelper + /// + public static class ConfigurationHelper + { + /// + /// Reads an xml configuration file from the file system + /// It will immediately re-serialize and save if new serialization data is available due to property changes + /// + /// The type. + /// The path. + /// The XML serializer. + /// System.Object. + public static object GetXmlConfiguration(Type type, string path, IXmlSerializer xmlSerializer, IFileSystem fileSystem) + { + object configuration; + + byte[] buffer = null; + + // Use try/catch to avoid the extra file system lookup using File.Exists + try + { + buffer = fileSystem.ReadAllBytes(path); + + configuration = xmlSerializer.DeserializeFromBytes(type, buffer); + } + catch (Exception) + { + configuration = Activator.CreateInstance(type); + } + + using (var stream = new MemoryStream()) + { + xmlSerializer.SerializeToStream(configuration, stream); + + // Take the object we just got and serialize it back to bytes + var newBytes = stream.ToArray(); + + // If the file didn't exist before, or if something has changed, re-save + if (buffer == null || !buffer.SequenceEqual(newBytes)) + { + fileSystem.CreateDirectory(Path.GetDirectoryName(path)); + + // Save it after load in case we got new items + fileSystem.WriteAllBytes(path, newBytes); + } + + return configuration; + } + } + } +} -- cgit v1.2.3