首页 新闻 会员 周边

使用 JSON 保存软件设置,每次保存都需要要重写整个文件吗?

0
悬赏园豆:15 [待解决问题]

保存设置这个功能如何实现最好呢,设置项很少的时候没有什么卡顿,如果很多的时候该怎么去做?
是分很多个设置文件吗?

private async void button_save_as_JSON_Click(object sender, EventArgs e)
{
    var JSON_String = new JsonObject();
    JSON_String.Add(nameof(JSON_Is_Active), this.JSON_Is_Active);
    JSON_String.Add(nameof(JSON_Ip_Address), this.JSON_Ip_Address);
    JSON_String.Add(nameof(JSON_Port), this.JSON_Port);
    JSON_String.Add(nameof(JSON_Socket_Receive_Buffer_Size), this.JSON_Socket_Receive_Buffer_Size);
    JSON_String.Add(nameof(JSON_Device_Id), this.JSON_Device_Id);
    JSON_String.Add(nameof(JSON_cam_1_trig_delay), this.JSON_cam_1_trig_delay);
    JSON_String.Add(nameof(JSON_cam_2_trig_delay), this.JSON_cam_2_trig_delay);

    if (File.Exists(this.JSON_Save_Path))
    {
        File.Delete(JSON_Save_Path);
    }

    // Create a file to write to.
    using (FileStream FS = File.Create(JSON_Save_Path))
    { 
        var options = new JsonSerializerOptions { WriteIndented = true };
        await JsonSerializer.SerializeAsync(FS, JSON_String, options);
        await FS.DisposeAsync();     
    }

    MessageBox.Show("保存成功!");
}
HeathWang的主页 HeathWang | 初学一级 | 园豆:155
提问于:2023-09-21 15:39
< >
分享
所有回答(3)
1

//如果配置非常的多,建议拆分。感觉你这个应该不用拆分。下面的代码仅提供一种思路,希望能帮到你。

using Newtonsoft.Json;

private async void button_save_as_JSON_Click(object sender, EventArgs e)
{
//新建一个配置类,在这里实例化好并赋值
// .... 转换后的json内容传入保存
ConfigJson configJson=new ConfigJson (xx,xx,xx,xx) // 类里写好构造函数
// 将configJson 这个用newtonsoftjson的转换成字符串jsonConfigStr的搞一下,具体的是啥,我忘记了,纯手打,你搜一下

 await SaveAsJsonAsync(jsonConfigStr).ConfigureAwait(false);

}

private async Task SaveAsJsonAsync()
{
if (File.Exists(this.JSON_Save_Path))
{
File.Delete(JSON_Save_Path);
}

// Create a file to write to.
using (FileStream FS = File.Create(JSON_Save_Path))
{ 
    var options = new JsonSerializerOptions { WriteIndented = true };
    await JsonSerializer.SerializeAsync(FS, JSON_String, options);
    await FS.DisposeAsync().ConfigureAwait(false); 
}

MessageBox.Show("保存成功!");
}

}

大楚打码人 | 园豆:4313 (老鸟四级) | 2023-09-21 16:56
2

在现代计算上, 几Kb或者几Mb的数据的json序列化和文件保存, 对于人的delay感知基本没有. 完全不用担心.

czd890 | 园豆:14412 (专家六级) | 2023-09-22 13:43
0

我想到的办法是进度条...

HeathWang | 园豆:155 (初学一级) | 2023-09-25 09:05
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册