67 lines
1.7 KiB
C#
67 lines
1.7 KiB
C#
|
|
using System;
|
||
|
|
using System.IO;
|
||
|
|
using System.Text;
|
||
|
|
using DCIT.Core.Models;
|
||
|
|
using Newtonsoft.Json;
|
||
|
|
|
||
|
|
namespace DCIT.Core.Services
|
||
|
|
{
|
||
|
|
public class ConfigurationService
|
||
|
|
{
|
||
|
|
private readonly string _configPath;
|
||
|
|
|
||
|
|
public ConfigurationService(string startupDirectory)
|
||
|
|
{
|
||
|
|
_configPath = Path.Combine(startupDirectory, "config.json");
|
||
|
|
}
|
||
|
|
|
||
|
|
public string ConfigPath
|
||
|
|
{
|
||
|
|
get { return _configPath; }
|
||
|
|
}
|
||
|
|
|
||
|
|
public ConfigurationLoadResult Load()
|
||
|
|
{
|
||
|
|
if (!File.Exists(_configPath))
|
||
|
|
{
|
||
|
|
return new ConfigurationLoadResult
|
||
|
|
{
|
||
|
|
Config = CreateDefault(),
|
||
|
|
IsMissing = true,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var content = File.ReadAllText(_configPath, Encoding.UTF8);
|
||
|
|
var config = JsonConvert.DeserializeObject<AppConfig>(content) ?? CreateDefault();
|
||
|
|
return new ConfigurationLoadResult
|
||
|
|
{
|
||
|
|
Config = config,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
return new ConfigurationLoadResult
|
||
|
|
{
|
||
|
|
Config = CreateDefault(),
|
||
|
|
IsCorrupted = true,
|
||
|
|
ErrorMessage = ex.Message,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Save(AppConfig config)
|
||
|
|
{
|
||
|
|
config.SavedAt = DateTime.Now;
|
||
|
|
var content = JsonConvert.SerializeObject(config, Formatting.Indented);
|
||
|
|
File.WriteAllText(_configPath, content, new UTF8Encoding(false));
|
||
|
|
}
|
||
|
|
|
||
|
|
public AppConfig CreateDefault()
|
||
|
|
{
|
||
|
|
return new AppConfig();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|