first commit
This commit is contained in:
66
DCIT.Core/Services/ConfigurationService.cs
Normal file
66
DCIT.Core/Services/ConfigurationService.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user