1.在NuGet安装Newtonsoft.Json(这里只用到解码);
2.窗体设计
3.代码
using System.IO; //using Newtonsoft.Json; using Newtonsoft.Json.Linq;
private void UserLogin_Load(object sender, EventArgs e) { ReadJson();//读取配置文件 } private void ReadJson() {//读取配置文件 string jsonPath = Application.StartupPath + @"userInfo.json"; if (File.Exists(jsonPath)) { try { string jsonStr = File.ReadAllText(jsonPath); JObject jsonObj = JObject.Parse(jsonStr); if (jsonObj != null) {//读取用户信息 if (jsonObj["id"] != null) { switch (jsonObj["id"].ToString()) {//是否记住用户信息 case "0"://不记住登陆信息 RdbNotSave.Checked = true; break; case "1"://记住账号 RdbSaveUserName.Checked = true; break; case "2"://记住账号和密码 RdbSaveBoth.Checked = true; break; default: RdbNotSave.Checked = false; RdbSaveUserName.Checked = false; RdbSaveBoth.Checked = false; break; } } if (jsonObj["userName"] != null) { TxbUsername.Text = jsonObj["userName"].ToString(); } if (jsonObj["passWord"] != null) { TxbPassword.Text = jsonObj["passWord"].ToString(); } } } catch { } } } private void WriteJson(string id, string userName, string passWord) {//写入配置文件 string jsonPath = Application.StartupPath + @"userInfo.json"; string jsonStr = "{"id":"" + id + "","userName":"" + userName + "","passWord":"" + passWord + ""}"; File.WriteAllText(jsonPath, jsonStr); } private void BtnLogin_Click(object sender, EventArgs e) {//登录按钮 //连接数据库进行登录检测,这里操作数据库代码省略if (/**/) {//登成功 //判断记录状态 if (RdbNotSave.Checked) {//不记住登陆信息 WriteJson("0", "", ""); } else if (RdbSaveUserName.Checked) {//记住账号 WriteJson("1", TxbUsername.Text.Trim(), ""); } else if (RdbSaveBoth.Checked) {//记住账号和密码 WriteJson("2", TxbUsername.Text.Trim(), TxbPassword.Text.Trim()); } } } private void BtnCancel_Click(object sender, EventArgs e) {//退出按钮 Environment.Exit(0);//退出软件 }
4:josn文件内容
{"id":"2","userName":"a","passWord":"2"}