一个简单的Dictionary格式JSON序列化参数保存程序

把参数通过Dictionary格式序列化保存为Json文件,同时读取文件功能

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Text;
using System.IO;
using System.Collections.Generic;

namespace JSON_CSHARP
{
    
    public partial class Form1 : Form
    {
        string FilePath="D:\\js1.json";//文本路径
        static  object log_lock=new object();//线程锁
        string sr;
        public Form1()
        {
            InitializeComponent();
        }
        //读取参数
        private void Loadbt_Click(object sender, EventArgs e)
        {
           

            string data = read_log_file(FilePath);//读取配置文件
            if (data != "")
            {
                Dictionary<string, string> dtr = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);//反序列化转换为dictionary
                //加载到输出文本框
                textBox1.Text = "";
                foreach (var dtr1 in dtr)
                {
                    textBox1.Text += dtr1.Key.ToString() + "  " + dtr1.Value.ToString() + "\r\n";
                }
            }
        }
        public static void save_log_file(string filePath, string mes)
        {
            lock (log_lock)
            {
                FileStream fs = new FileStream(filePath, FileMode.Create);//保存到文件创建或覆盖文件
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                //开始写入
                sw.Write(mes);
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();
            }
        }
        //保存参数

        private void Savebt_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> dt = new Dictionary<string, string>();//保存各个参数
            dt.Add(K1.Name, Value1.Text);
            dt.Add(K2.Name, Value2.Text);
            dt.Add(K3.Name, Value3.Text);
            dt.Add(K4.Name, Value4.Text);
            sr = JsonConvert.SerializeObject(dt);//序列化参数
            save_log_file(FilePath, sr);//写入保存文件
        }
        public static string read_log_file(string filePath)
        {
            if (!File.Exists(filePath)) return "";
            StreamReader sr = new StreamReader(filePath, Encoding.UTF8);
            String line;
            String log = "";
            while ((line = sr.ReadLine()) != null)
            {
                log += line;
            }
            sr.Close();

            return log;

        }

       
    }
}
复制代码

 

posted @   为啥呢  阅读(248)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示