jellyfin/MediaBrowser.Common.Implementations/Configuration/ConfigurationHelper.cs

61 lines
2.0 KiB
C#
Raw Normal View History

2013-03-04 05:43:06 +00:00
using MediaBrowser.Model.Serialization;
using System;
using System.IO;
using System.Linq;
2015-09-13 21:32:02 +00:00
using MediaBrowser.Common.IO;
2013-03-04 05:43:06 +00:00
2014-12-26 19:34:39 +00:00
namespace MediaBrowser.Common.Implementations.Configuration
2013-03-04 05:43:06 +00:00
{
/// <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>
2015-09-13 21:32:02 +00:00
public static object GetXmlConfiguration(Type type, string path, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
2013-03-04 05:43:06 +00:00
{
object configuration;
byte[] buffer = null;
// Use try/catch to avoid the extra file system lookup using File.Exists
try
{
2015-09-13 21:32:02 +00:00
buffer = fileSystem.ReadAllBytes(path);
2013-03-04 05:43:06 +00:00
configuration = xmlSerializer.DeserializeFromBytes(type, buffer);
}
2013-07-16 16:03:28 +00:00
catch (Exception)
2013-03-04 05:43:06 +00:00
{
configuration = Activator.CreateInstance(type);
}
2014-08-05 03:41:56 +00:00
using (var stream = new MemoryStream())
2013-03-04 05:43:06 +00:00
{
2014-08-05 03:41:56 +00:00
xmlSerializer.SerializeToStream(configuration, stream);
2013-03-04 05:43:06 +00:00
2014-08-05 03:41:56 +00:00
// 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))
{
2015-09-13 21:32:02 +00:00
fileSystem.CreateDirectory(Path.GetDirectoryName(path));
2013-03-04 05:43:06 +00:00
2014-08-05 03:41:56 +00:00
// Save it after load in case we got new items
2015-09-13 21:32:02 +00:00
fileSystem.WriteAllBytes(path, newBytes);
2014-08-05 03:41:56 +00:00
}
return configuration;
}
}
2013-03-04 05:43:06 +00:00
}
}