Created
November 15, 2019 15:30
-
-
Save savaged/0653262410d39eab68e1cf2d29210989 to your computer and use it in GitHub Desktop.
Local Cached Properties Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Reflection; | |
using Newtonsoft.Json; | |
namespace savaged.Services.IO | |
{ | |
class PropertiesService : IPropertiesService | |
{ | |
private IDictionary<string, object> _props; | |
private bool _isInitialised; | |
public PropertiesService() | |
{ | |
_props = new Dictionary<string, object>(); | |
FileLocation = Path.Combine( | |
Environment.GetFolderPath( | |
Environment.SpecialFolder.LocalApplicationData), | |
Assembly.GetEntryAssembly().GetName().Name, | |
"props.json"); | |
} | |
public void Initialise(string fileLocation = "") | |
{ | |
if (_isInitialised) return; | |
if (!string.IsNullOrEmpty(fileLocation)) | |
{ | |
FileLocation = fileLocation; | |
} | |
var fileInfo = new FileInfo(FileLocation); | |
if (fileInfo.Exists) | |
{ | |
_props = JsonConvert | |
.DeserializeObject<IDictionary<string, object>>( | |
File.ReadAllText(FileLocation)); | |
} | |
else | |
{ | |
if (!fileInfo.Directory.Exists) | |
{ | |
fileInfo.Directory.Create(); | |
} | |
File.WriteAllText( | |
FileLocation, | |
JsonConvert.SerializeObject(_props)); | |
} | |
_isInitialised = true; | |
} | |
public string FileLocation { get; private set; } | |
public object Get(string key) | |
{ | |
Initialise(); | |
if (_props.Keys.Contains(key)) | |
{ | |
return _props[key]; | |
} | |
return null; | |
} | |
public void Set(string key, object value) | |
{ | |
Initialise(); | |
if (_props.Keys.Contains(key)) | |
{ | |
_props[key] = value; | |
} | |
else | |
{ | |
_props.Add(key, value); | |
} | |
var fileInfo = new FileInfo(FileLocation); | |
if (fileInfo.Exists) | |
{ | |
File.Delete(FileLocation); | |
} | |
var json = JsonConvert.SerializeObject(_props); | |
File.WriteAllText(FileLocation, json); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment