using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace QMAPP.WinForm.Common
{
///
/// 工控机本地设置
///
public class LocalSetting
{
private const string filename = "LocalSetting.cfg";
private static Dictionary _settinglist;
private static LocalSetting _settings = null;
///
/// 本地配置
///
public static LocalSetting Settings
{
get {
if (_settings == null)
{
_settings = new LocalSetting();
}
return _settings;
}
}
private LocalSetting()
{
Load();
}
///
/// 加载配置
///
private static void Load()
{
string filepath = ConfigurationManager.AppSettings["SaveFilePath"];
filepath = string.Format("{0}\\{1}", filepath.TrimEnd('\\'), filename);
if (System.IO.File.Exists(filepath))
{
string settingstring = System.IO.File.ReadAllText(filepath);
_settinglist = Newtonsoft.Json.JsonConvert.DeserializeObject>(settingstring);
}
if (_settinglist == null)
{
_settinglist = new Dictionary();
}
}
///
/// 保存配置
///
private static void Save()
{
if (_settinglist != null)
{
string filepath = ConfigurationManager.AppSettings["SaveFilePath"];
filepath = string.Format("{0}\\{1}", filepath.TrimEnd('\\'), filename);
string settingstring = Newtonsoft.Json.JsonConvert.SerializeObject(_settinglist);
System.IO.File.WriteAllText(filepath, settingstring);
}
}
///
/// 获取或设置本地配置值
///
/// key
///
public string this[string key]
{
get
{
if (_settinglist != null && _settinglist.ContainsKey(key))
{
return _settinglist[key];
}
return null;
}
set
{
if (_settinglist != null)
{
if (!_settinglist.ContainsKey(key))
{
_settinglist.Add(key, value);
}
else
{
_settinglist[key] = value;}
Save();
}
}
}
///
/// 获取或设置本地配置值,如果不存在配置则返回默认值并保存
///
/// key
/// 默认值
///
public string this[string key,string defvalue]
{
get
{
if (_settinglist != null)
{
if (!_settinglist.ContainsKey(key))
{
_settinglist.Add(key, defvalue);
Save();
}
return _settinglist[key];
}
return null;
}
set
{
if (_settinglist != null)
{
if (!_settinglist.ContainsKey(key))
{
_settinglist.Add(key, value);
}
else
{
_settinglist[key] = value;
}
Save();
}
}
}
}
}