简体   繁体   English

如何在 C# 的运行时保存多个用户设置

[英]How do I save multiple user settings in runtime in C#

I am trying to make my app stay the way I left it after closing the app.我试图让我的应用程序在关闭应用程序后保持原样。 Therefore I want to save set of items from ListView to the settings and I can't figure out how to do that.因此,我想将 ListView 中的一组项目保存到设置中,但我不知道该怎么做。 I've found some solutions but I believe they are outdated as they don't seem to work.我找到了一些解决方案,但我相信它们已经过时,因为它们似乎不起作用。

Image shows set of items in ListView which I want to save so they appear there after restarting the app:图像显示了我要保存的 ListView 中的一组项目,以便它们在重新启动应用程序后出现:

Items项目

This is where I want them to appear:这是我希望它们出现的地方:

Settings设置

And this is part of code that I've tried out so far这是我迄今为止尝试过的代码的一部分

 private void btn_SaveConfig_Click(object sender, EventArgs e)
    {
        int i = 0;
        Settings.Default["IP"] = tBox_discoverServerFrom.Text;
        Settings.Default["DiscoveredServers"] = cBox_discoveredServers.Text;
        foreach (var item in lV_groups.Items)
        {
            var property = new System.Configuration.SettingsProperty("Group"+i);
            property.PropertyType = typeof(string);
            property.Name = "Group " + i;
            Settings.Default.Properties.Add(property);
            Settings.Default.Save();
            i++;
        }
    }

I do not think using the Settings API is a great idea if you want to save any significant amount of data.如果您想保存大量数据,我认为使用设置 API 不是一个好主意。

I would recommend the following我会推荐以下

  1. Create a class describing all the data you want to save.创建一个 class 描述您要保存的所有数据。 To make serialization easier it should have a parameter less constructor and public setters for all properties.为了使序列化更容易,它应该有一个参数少的构造函数和所有属性的公共设置器。 This is sometimes called a Data-Transfer-Object (DTO)这有时称为数据传输对象 (DTO)
  2. Use json to serialize the object to a file.使用json将 object 序列化为文件。 You would normally place the file in a subfolder in the local app data folder: Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) .您通常会将文件放在本地应用程序数据文件夹中的子文件夹中: Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
  3. Do the reverse when you start the application.启动应用程序时执行相反的操作。 If there is a file, use Json to deserialize it and use it however you want.如果有文件,请使用 Json 对其进行反序列化并根据需要使用它。
  4. You may optionally add logic to save the file periodically, this would allow recovery in case of application crashes.您可以选择添加逻辑以定期保存文件,这将允许在应用程序崩溃的情况下进行恢复。 You might also want some system to keep more than one file, in case the application or computer crashes in the middle of a save operation, and the file becomes corrupt.您可能还希望某些系统保留多个文件,以防应用程序或计算机在保存操作过程中崩溃,并且文件损坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM