简体   繁体   中英

How can i save settings of my app to a text file and read them back on load?

Read them back in app constructor and also maybe in other places in program. I have a new form i created with some checkboxes:

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 System.IO;

namespace Options
{
    public partial class OptionsMenuForm : Form
    {


        public OptionsMenuForm()
        {
            InitializeComponent();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                Settings.downloadonstart = true;
            }
            else
            {
                Settings.downloadonstart = false;
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked)
            {
                Settings.loadonstart = true;
            }
            else
            {
                Settings.loadonstart = false;
            }
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox3.Checked)
            {
                Settings.startminimized = true;
            }
            else
            {
                Settings.startminimized = false;
            }
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox4.Checked)
            {
                Settings.displaynotifications = true;
            }
            else
            {
                Settings.displaynotifications = false;
            }
        }
    }
}

Now i want to save each time the state of one/any of the checkboxes. I also added a class i'm using th pass the variables between the new form and form1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Options
{
    class Settings
    {
        public static bool downloadonstart;
        public static bool loadonstart;
        public static bool startminimized;
        public static bool displaynotifications;
    }
}

Now how can i use this in form1 by saving the settings to a text file ? For example in the text file the content will be something like:

CheckBox1 = true
CheckBox2 = false
CheckBox3 = false
CheckBox4 = true

And then if i change the state of one of them it will write it in the text file:

CheckBox1 = false
CheckBox2 = false
CheckBox3 = true
CheckBox4 = true

In form1 top i added

string settingsFile = "settings.txt";
string settingsFileDirectory = "\\settings";
StreamWriter writetosettingsfile;

Then in constructor

settingsFileDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) +
                settingsFileDirectory;
            if (!Directory.Exists(settingsFileDirectory))
            {
                Directory.CreateDirectory(settingsFileDirectory);
            }

I know the app it self have a settings in the properties but i wanted to use a text file this time since i have many settings and i might have more later.

Or using the settings in the app in properties i did:

设置

But now how do i use with it in my program to save every checkbox state in the new form and then using it in form1 ?

You can use json.net

Something like this to save the data

private void Form1_Load(object sender, EventArgs e)
{
    checkBox1.CheckedChanged += checkBox_CheckedChanged;
    checkBox2.CheckedChanged += checkBox_CheckedChanged;
    checkBox3.CheckedChanged += checkBox_CheckedChanged;
    checkBox4.CheckedChanged += checkBox_CheckedChanged;
}

private void checkBox_CheckedChanged(object sender, EventArgs e)
{
    var settings = new Settings();
    settings.downloadonstart = checkBox1.Checked;
    settings.loadonstart = checkBox2.Checked;
    settings.startminimized = checkBox3.Checked;
    settings.displaynotifications = checkBox4.Checked;
    File.WriteAllText(@"c:\configfile.json", JsonConvert.SerializeObject(settings));
}

You can read the file like this

Settings settings = JsonConvert.DeserializeObject<Settings>(File.ReadAllText(@"c:\configfile.json"));

Documentation: http://www.newtonsoft.com/json/help/html/Introduction.htm

public OptionsMenuForm()
{
    InitializeComponent();
    //Read the settings from a file with comma delimited 1's and 0's or whatever you like
    string[] values = System.IO.File.ReadAllText("c:\temp\a.txt").Split(',');
    checkBox1.Checked = Convert.ToBoolean(Convert.ToInt32(values[0]));
    checkBox2.Checked = Convert.ToBoolean(Convert.ToInt32(values[1]));;

    //On checkbox changes save the settings
    checkBox1.CheckedChanged +=SaveSettings;
    checkBox2.CheckedChanged +=SaveSettings;
}

public void SaveSettings(object sender,EventArgs e)
{
    StringBuilder sbValues = new StringBuilder();
    int i = 0;

    i = checkBox1.Checked ? 1 : 0;
    sbValues.Append(i.ToString() + ",");

    i = checkBox2.Checked ? 1 : 0;
    sbValues.Append(i.ToString() + ",");

    System.IO.File.WriteAllText("c:\temp\a.txt",sbValues.ToString());
}

It is recommended that you use XML when using the .NET framework.

public static void ConvertStringToXmlList()
{
    XElement xml = new XElement
        (
            "Items",
            (
                from x in [YourList] select new XElement("Item", x)
            )
        );
    XDocument doc = new XDocument
        (
            xml
        );
    doc.Save(Environment.CurrentDirectory + "/settings.xml");  
}



var xmlReader = new XmlTextReader("settings.xml");
while (xmlReader.Read()) 
{
    switch (reader.NodeType) 
    {
       case [nodetype]:
           // Code here
       break;
    }
}

Also, instead of creating the same event for all four checkbox's, just use 1.

Inside of the single event put:

ckCheckBox1.Checked = !ckCheckBox1.Checked;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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