You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
2.1 KiB
91 lines
2.1 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.Configuration;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace PUtility
|
|
{
|
|
public class AppSetting
|
|
{
|
|
public static AppSetting Default { get; set; } = new AppSetting();
|
|
|
|
public string ConfigFileName { get; private set; }
|
|
private Configuration configuration;
|
|
public Configuration Config
|
|
{
|
|
get
|
|
{
|
|
if (configuration == null)
|
|
{
|
|
if (string.IsNullOrEmpty(ConfigFileName))
|
|
{
|
|
configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
|
|
}
|
|
else
|
|
{
|
|
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
|
|
configMap.ExeConfigFilename = this.ConfigFileName;
|
|
configuration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
|
|
}
|
|
}
|
|
|
|
return configuration;
|
|
}
|
|
}
|
|
|
|
public AppSetting(string fileName = null)
|
|
{
|
|
InitInstance(fileName);
|
|
}
|
|
|
|
private void InitInstance(string fileName)
|
|
{
|
|
this.ConfigFileName = fileName;
|
|
}
|
|
|
|
public void Refresh()
|
|
{
|
|
configuration = null;
|
|
}
|
|
|
|
public T GetValue<T>(string key, T defaultValue)
|
|
{
|
|
if (this.Config.AppSettings.Settings[key] == null)
|
|
return defaultValue;
|
|
|
|
string source = this.Config.AppSettings.Settings[key].Value;
|
|
|
|
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
|
|
try
|
|
{
|
|
return (T)converter.ConvertFromString(source);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
PFileManager.Instance.WriteLog($"AppSetting.GetValue Exception: {ex.Message}");
|
|
return defaultValue;
|
|
}
|
|
}
|
|
|
|
public void SetValue<T>(string key, T value)
|
|
{
|
|
Refresh();
|
|
|
|
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
|
|
string valueString = converter.ConvertToString(value);
|
|
|
|
if (this.Config.AppSettings.Settings[key] == null)
|
|
this.Config.AppSettings.Settings.Add(key, valueString);
|
|
else
|
|
this.Config.AppSettings.Settings[key].Value = valueString;
|
|
|
|
this.Config.Save();
|
|
|
|
if (string.IsNullOrEmpty(ConfigFileName))
|
|
ConfigurationManager.RefreshSection("appSettings");
|
|
}
|
|
}
|
|
}
|
|
|