C#--使用json配置檔案方法【讀寫Json,適合小專案】
阿新 • • 發佈:2021-12-05
1,DAL中新增幫助類JsonConfigHelper
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; /* * 需要新增引用Newtonsoft.Json.dl */ namespace KobelcoReportDAL { public class JsonConfigHelper { private static Dictionary<string, string> configDic = new Dictionary<string, string>(); /// <summary> /// 讀取配置資訊 /// </summary> /// <param name="key"></param> /// <returns></returns> public static string ReadConfig(string key) { if (File.Exists("config.json") == false)//如果不存在就建立file資料夾 { FileStream f = File.Create("config.json"); f.Close(); } string s = File.ReadAllText("config.json"); try { configDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(s); } catch { configDic = new Dictionary<string, string>(); } if (configDic != null && configDic.ContainsKey(key)) { return configDic[key]; } else { return string.Empty; } } /// <summary> /// 新增配置資訊 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void WriteConfig(string key, string value) { if (configDic == null) { configDic = new Dictionary<string, string>(); } configDic[key] = value; string s = JsonConvert.SerializeObject(configDic); File.WriteAllText("config.json", s); } /// <summary> /// 刪除配置資訊 /// </summary> /// <param name="key"></param> public static void DeleteConfig(string key) { if (configDic != null && configDic.ContainsKey(key)) { configDic.Remove(key); string s = JsonConvert.SerializeObject(configDic); File.WriteAllText("config.json", s); } } } }
2,讀取配置檔案【窗體載入的時候】
//【1】讀取配置檔案 filePath.RefFilePath = JsonConfigHelper.ReadConfig(this.txt_ReferenceFilePath.Name); filePath.MatchFilePath= JsonConfigHelper.ReadConfig(this.txt_MatchingFilePath.Name); filePath.AtlasDataFilePath= JsonConfigHelper.ReadConfig(this.txt_AtlasFilePath.Name); //【2】為控制元件賦值 this.txt_ReferenceFilePath.Text= filePath.RefFilePath; this.txt_MatchingFilePath.Text = filePath.MatchFilePath; this.txt_AtlasFilePath.Text = filePath.AtlasDataFilePath;
3,修改配置檔案【修改儲存按鈕】
//修改配置檔案 private void btn_modify_Click(object sender, EventArgs e) { JsonConfigHelper.WriteConfig(this.txt_ReferenceFilePath.Name, this.txt_ReferenceFilePath.Text); JsonConfigHelper.WriteConfig(this.txt_MatchingFilePath.Name, this.txt_MatchingFilePath.Text); JsonConfigHelper.WriteConfig(this.txt_AtlasFilePath.Name, this.txt_AtlasFilePath.Text); }
4,儲存的配置檔案位置