diff options
| author | LukePulverenti <luke.pulverenti@gmail.com> | 2013-03-04 00:43:06 -0500 |
|---|---|---|
| committer | LukePulverenti <luke.pulverenti@gmail.com> | 2013-03-04 00:43:06 -0500 |
| commit | 2ca4b7d03adfa3cc7c9c6a597a11762142d5b34b (patch) | |
| tree | 18a3d756bd6333a863ccb6d48161b97bb4c2d83a /MediaBrowser.Common/Configuration/ConfigurationHelper.cs | |
| parent | 401b56c732f7b22bce844770f75fcddbcc803092 (diff) | |
Created IConfigurationManager
Diffstat (limited to 'MediaBrowser.Common/Configuration/ConfigurationHelper.cs')
| -rw-r--r-- | MediaBrowser.Common/Configuration/ConfigurationHelper.cs | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/MediaBrowser.Common/Configuration/ConfigurationHelper.cs b/MediaBrowser.Common/Configuration/ConfigurationHelper.cs new file mode 100644 index 000000000..fc74a6a4d --- /dev/null +++ b/MediaBrowser.Common/Configuration/ConfigurationHelper.cs @@ -0,0 +1,68 @@ +using MediaBrowser.Model.Serialization; +using System; +using System.IO; +using System.Linq; + +namespace MediaBrowser.Common.Configuration +{ + /// <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) + { + object configuration; + + byte[] buffer = null; + + // Use try/catch to avoid the extra file system lookup using File.Exists + try + { + buffer = File.ReadAllBytes(path); + + configuration = xmlSerializer.DeserializeFromBytes(type, buffer); + } + catch (FileNotFoundException) + { + configuration = Activator.CreateInstance(type); + } + + // Take the object we just got and serialize it back to bytes + var newBytes = xmlSerializer.SerializeToBytes(configuration); + + // If the file didn't exist before, or if something has changed, re-save + if (buffer == null || !buffer.SequenceEqual(newBytes)) + { + // Save it after load in case we got new items + File.WriteAllBytes(path, newBytes); + } + + return configuration; + } + + + /// <summary> + /// Reads an xml configuration file from the file system + /// It will immediately save the configuration after loading it, just + /// in case there are new serializable properties + /// </summary> + /// <typeparam name="T"></typeparam> + /// <param name="path">The path.</param> + /// <param name="xmlSerializer">The XML serializer.</param> + /// <returns>``0.</returns> + public static T GetXmlConfiguration<T>(string path, IXmlSerializer xmlSerializer) + where T : class + { + return GetXmlConfiguration(typeof(T), path, xmlSerializer) as T; + } + } +} |
