json配置文件:
{
"ConnectionStrings": {
"Default": "Data Source=./print_infos.db;Mode=ReadWriteCreate;Cache=Default;"
},
"IsAutoBoot": false,
"TopMost": true
}
窗体加载事件中,通过读取配置文件得到是否开启开机自动启动,给单选框选中或不选中
ck_Selfstart.Checked=readJson("IsAutoBoot");
单选框checkbox的changed事件:
当单选框选中时,将程序添加至注册表中,未选中时从注册表中移除。并修改配置文件中IsAutoBoot的值。
private void ck_Selfstart_CheckedChanged(object sender, EventArgs e)
{
try
{
string execPath = Application.ExecutablePath;
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
if (ck_Selfstart.Checked)
{
rk2.SetValue("MyExec", execPath);
Log.Information(string.Format("[注册表操作]添加注册表键值:path = {0}, key = {1}, value = {2} 成功", rk2.Name, "TuniuAutoboot", execPath));
}
else
{
rk2.DeleteValue("MyExec", false);
Log.Information(string.Format("[注册表操作]删除注册表键值:path = {0}, key = {1} 成功", rk2.Name, "TuniuAutoboot"));
}
rk2.Close();
rk.Close();
WriteJson("IsAutoBoot", ck_Selfstart.Checked);
}
catch (Exception ex)
{
Log.Debug(string.Format("[注册表操作]向注册表写开机启动信息失败, Exception: {0}", ex.Message));
}
}
读取json和写入json,将是否开机自启,数据持久化
/// <summary>
/// 读取json,是否开机自启
/// </summary>
private bool readJson(string key)
{
try
{
string path = Application.StartupPath + @"\appsettings.json";
StreamReader streamReader = new StreamReader(path);
string jsonStr = streamReader.ReadToEnd();
dynamic jsonObj = JsonConvert.DeserializeObject<dynamic>(jsonStr);
streamReader.Close();
return (bool)jsonObj[key];
}
catch (Exception e)
{
MessageBox.Show(e.Message + "/r/n" + e.StackTrace);
Log.Debug($"读取json错误:{e.Message}");
}
return false;
}
/// <summary>
/// 修改json
/// </summary>
private void WriteJson(string key,bool isAutoBoot)
{
try
{
string path = Application.StartupPath + @"\appsettings.json";
StreamReader streamReader = new StreamReader(path);
dynamic jsonObj = JsonConvert.DeserializeObject<dynamic>(streamReader.ReadToEnd());
jsonObj[key] = isAutoBoot;
streamReader.Close();
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText(path, output);
}
catch (Exception e)
{
MessageBox.Show(e.Message + "/r/n" + e.StackTrace);
Log.Debug($"写入json错误:{e.Message}");
}
}