using MediaBrowser.Model.Serialization;
using System;
using System.IO;
using System.Linq;
namespace MediaBrowser.Common.Configuration
{
///
/// 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)
{
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 (Exception)
{
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))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
// Save it after load in case we got new items
File.WriteAllBytes(path, newBytes);
}
return configuration;
}
///
/// 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
///
///
/// The path.
/// The XML serializer.
/// ``0.
public static T GetXmlConfiguration(string path, IXmlSerializer xmlSerializer)
where T : class
{
return GetXmlConfiguration(typeof(T), path, xmlSerializer) as T;
}
}
}