2019-01-06 20:50:43 +00:00
|
|
|
using System;
|
2016-10-29 05:40:15 +00:00
|
|
|
using System.IO;
|
|
|
|
using System.Linq;
|
|
|
|
using MediaBrowser.Model.Serialization;
|
|
|
|
|
2017-02-20 20:50:58 +00:00
|
|
|
namespace Emby.Server.Implementations.AppBase
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
/// <summary>
|
2019-10-25 10:47:20 +00:00
|
|
|
/// Class ConfigurationHelper.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
|
|
|
public static class ConfigurationHelper
|
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// Reads an xml configuration file from the file system
|
2019-10-25 10:47:20 +00:00
|
|
|
/// It will immediately re-serialize and save if new serialization data is available due to property changes.
|
2016-10-29 05:40:15 +00:00
|
|
|
/// </summary>
|
|
|
|
/// <param name="type">The type.</param>
|
|
|
|
/// <param name="path">The path.</param>
|
|
|
|
/// <param name="xmlSerializer">The XML serializer.</param>
|
|
|
|
/// <returns>System.Object.</returns>
|
2019-02-06 19:38:42 +00:00
|
|
|
public static object GetXmlConfiguration(Type type, string path, IXmlSerializer xmlSerializer)
|
2016-10-29 05:40:15 +00:00
|
|
|
{
|
|
|
|
object configuration;
|
|
|
|
|
|
|
|
byte[] buffer = null;
|
|
|
|
|
|
|
|
// Use try/catch to avoid the extra file system lookup using File.Exists
|
|
|
|
try
|
|
|
|
{
|
2019-01-26 22:09:07 +00:00
|
|
|
buffer = File.ReadAllBytes(path);
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
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))
|
|
|
|
{
|
2019-01-26 21:08:04 +00:00
|
|
|
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
2016-10-29 05:40:15 +00:00
|
|
|
|
|
|
|
// Save it after load in case we got new items
|
2019-01-26 22:09:07 +00:00
|
|
|
File.WriteAllBytes(path, newBytes);
|
2016-10-29 05:40:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return configuration;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|