Created
December 10, 2014 01:02
-
-
Save liulixiang1988/24fbf1a3814aab183cdc to your computer and use it in GitHub Desktop.
C# Config
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.ComponentModel; | |
using System.IO; | |
using Newtonsoft.Json; | |
namespace Liulx.Util | |
{ | |
public class Config: INotifyPropertyChanged | |
{ | |
private static readonly Config _default = new Config(); | |
public static Config Default | |
{ | |
get { return _default; } | |
} | |
public string MonitorFolder | |
{ | |
get { return GetString("MonitorFolder"); } | |
set | |
{ | |
if (GetString("MonitorFolder") != value) | |
{ | |
this["MonitorFolder"] = value; | |
OnPropertyChanged("MonitorFolder"); | |
} | |
} | |
} | |
public string LogFolder | |
{ | |
get { return GetString("LogFolder"); } | |
set | |
{ | |
if (GetString("LogFolder") != value) | |
{ | |
this["LogFolder"] = value; | |
OnPropertyChanged("LogFolder"); | |
} | |
} | |
} | |
#region Config Method | |
private readonly Dictionary<string, object> _configs; | |
private readonly string _fileName; | |
public Config(string fileName = "config.json") | |
{ | |
_fileName = fileName; | |
if (!File.Exists(_fileName)) | |
{ | |
_configs = new Dictionary<string, object>(); | |
File.CreateText(_fileName); | |
return; | |
} | |
_configs = JsonConvert.DeserializeObject<Dictionary<string, object>>(File.ReadAllText(_fileName)); | |
_configs = _configs ?? new Dictionary<string, object>(); | |
} | |
public object this[string index] | |
{ | |
get { return _configs.ContainsKey(index) ? _configs[index] : null; } | |
set { _configs[index] = value; } | |
} | |
public string GetString(string key) | |
{ | |
try | |
{ | |
return this[key] == null ? null : _configs[key].ToString(); | |
} | |
catch (Exception e) | |
{ | |
Log.CreateErrorMsg(e.Message); | |
} | |
return null; | |
} | |
public List<T> GetList<T>(string key) | |
{ | |
try | |
{ | |
return this[key] == null ? null : (List<T>) _configs[key]; | |
} | |
catch (Exception e) | |
{ | |
Log.CreateErrorMsg(e.Message); | |
} | |
return null; | |
} | |
public void Save() | |
{ | |
string json = JsonConvert.SerializeObject(_configs, Formatting.Indented); | |
File.WriteAllText(_fileName, json); | |
} | |
#endregion | |
#region INotifyPropertyChanged | |
public event PropertyChangedEventHandler PropertyChanged; | |
protected void OnPropertyChanged(string propertyName) | |
{ | |
if (PropertyChanged != null) | |
{ | |
PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment