public class AppConfigs
{
private static Lazy<AppConfigs> instance = new Lazy<AppConfigs>(() => new AppConfigs());
public static AppConfigs Instance = instance.Value;
private readonly Dictionary<string, Dictionary<string, string>> keyValuePairs = new Dictionary<string, Dictionary<string, string>>();
private readonly static string configPath = Path.Combine(System.Windows.Forms.Application.StartupPath, "Config", "设置");
private AppConfigs()
{
}
/// <summary>
/// 添加config文件
/// </summary>
/// <param name="configName"></param>
public static void AddConfig(string configName)
{
if (!Directory.Exists(configPath))
{
Directory.CreateDirectory(configPath);
}
using (var scope = new TransactionScope())
{
FileStream newfile = null;
if (!File.Exists(configName))
{
newfile = new FileStream(configName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite, 8, FileOptions.WriteThrough);
}
else
{
newfile = new FileStream(configName, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite, 8, FileOptions.WriteThrough);
}
var sw = new StreamWriter(newfile);
string s = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "\n" + "<configuration>" + "\n" + "<appSettings> " + "\n" + " </appSettings>" + "\n" + "</configuration>";
sw.Write(s);
sw.Close();
newfile.Close();
scope.Complete();
}
}
/// <summary>
/// 获取config文件参数
/// </summary>
/// <param name="configName"></param>
/// <param name="key"></param>
/// <param name="val"></param>
/// <returns></returns>
public string GetConfig(string configName, string key, string val = "0")
{
key = AesEncrypt(key);//加密
string path = Path.Combine(configPath, configName);
if (keyValuePairs.TryGetValue(configName, out var keyValues))
{
if (keyValues.TryGetValue(key, out var value))
{
return value;
}
}
if (File.Exists(path))
{
//判断是否需要备份文件
ConfigBackup.GetBackupFile(path);
var ecf = new ExeConfigurationFileMap
{
ExeConfigFilename = path
};
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
var keys = config.AppSettings.Settings.AllKeys.ToList();
if (keys == null || keys.Count == 0)
return val;
if (keys.Contains(key))
{
val = AesDecrypt(config.AppSettings.Settings[key].Value.ToString());//解密
}
else
{
string AESval = AesEncrypt(val);//加密
config.AppSettings.Settings.Add(key, AESval);
config.Save(ConfigurationSaveMode.Modified);
}
var pairs = new Dictionary<string, string>();
foreach (var item in keys)
{
pairs.Add(item.ToString(), AesDecrypt(config.AppSettings.Settings[item.ToString()].Value.ToString()));
}
if (keyValuePairs.ContainsKey(configName))
{
keyValuePairs[configName] = pairs;
}
else
{
keyValuePairs.Add(configName, pairs);
}
}
else
{
if (!File.Exists(path)) AddConfig(path);
var ecf = new ExeConfigurationFileMap
{
ExeConfigFilename = path
};
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
string AESval = AesEncrypt(val);//加密
config.AppSettings.Settings.Add(key, AESval);
config.Save(ConfigurationSaveMode.Modified);
}
if (!keyValuePairs.ContainsKey(configName))
{
var pair = new Dictionary<string, string>
{
{ key, val }
};
keyValuePairs.Add(configName, pair);
}
else if (keyValuePairs.ContainsKey(configName))
{
if (!keyValuePairs[configName].ContainsKey(key))
{
keyValuePairs[configName].Add(key, val);
}
}
return val;
}
/// <summary>
/// 设置config文件参数
/// </summary>
/// <param name="configName"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public void SetConfig(string configName, string key, string value = "1")
{
string path = Path.Combine(configPath, configName);
string AESval = AesEncrypt(value);//加密
key = AesEncrypt(key);//加密
if (keyValuePairs.ContainsKey(configName) && keyValuePairs[configName].ContainsKey(key))
{
if (keyValuePairs[configName][key] == value)
return;
}
//备份
ConfigBackup.CopyFile(path);
if (File.Exists(path))
{
var ecf = new ExeConfigurationFileMap
{
ExeConfigFilename = path
};
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] != null)
{
config.AppSettings.Settings[key].Value = AESval;
}
else
{
config.AppSettings.Settings.Add(key, AESval);
}
config.Save(ConfigurationSaveMode.Modified);
}
else
{
if (!File.Exists(path)) AddConfig(path);
var ecf = new ExeConfigurationFileMap
{
ExeConfigFilename = path
};
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
config.AppSettings.Settings.Add(key, AESval);
config.Save(ConfigurationSaveMode.Modified);
}
if (!keyValuePairs.ContainsKey(configName))
{
var pair = new Dictionary<string, string>
{
{ key, value }
};
keyValuePairs.Add(configName, pair);
}
else if (keyValuePairs.ContainsKey(configName))
{
if (!keyValuePairs[configName].ContainsKey(key))
{
keyValuePairs[configName].Add(key, value);
}
else
{
keyValuePairs[configName][key] = value;
}
}
ConfigurationManager.RefreshSection("appSettings");
}
private readonly string key = "niubiultruplus++";//必须16位
/// <summary>
/// AES 加密
/// </summary>
/// <param name="str">明文(待加密)</param>
/// <returns></returns>
public string AesEncrypt(string str)
{
if (string.IsNullOrEmpty(str)) return null;
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
var rm = new RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = rm.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
/// <summary>
/// AES 解密
/// </summary>
/// <param name="str">明文(待解密)</param>
/// <returns></returns>
public string AesDecrypt(string str)
{
if (string.IsNullOrEmpty(str)) return null;
Byte[] toEncryptArray = Convert.FromBase64String(str);
var rm = new RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = rm.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Encoding.UTF8.GetString(resultArray);
}
}