diff options
| author | Luke <luke.pulverenti@gmail.com> | 2017-02-20 15:52:54 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2017-02-20 15:52:54 -0500 |
| commit | 962a0f561d3e2accb847444542030e9b4aff0a27 (patch) | |
| tree | 8d0b34bae45d8204f6fd1514f6d565af2d3fa0d0 /Emby.Server.Implementations/AppBase/ConfigurationHelper.cs | |
| parent | 15df2ec3e985d506130a13147642f0e57f3e8754 (diff) | |
| parent | e7ebc598c894a0c491f6059b513a3d207595af5f (diff) | |
Merge pull request #2479 from MediaBrowser/dev
Dev
Diffstat (limited to 'Emby.Server.Implementations/AppBase/ConfigurationHelper.cs')
| -rw-r--r-- | Emby.Server.Implementations/AppBase/ConfigurationHelper.cs | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs new file mode 100644 index 0000000000..ad2f459459 --- /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 +{ + /// <summary> + /// Class ConfigurationHelper + /// </summary> + public static class ConfigurationHelper + { + /// <summary> + /// 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 + /// </summary> + /// <param name="type">The type.</param> + /// <param name="path">The path.</param> + /// <param name="xmlSerializer">The XML serializer.</param> + /// <returns>System.Object.</returns> + 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; + } + } + } +} |
