如何将我的应用设置保存到文本文件并在加载时重新阅读?

时间:2016-02-23 23:04:55

标签: c# .net winforms

在app构造函数中读取它们,也可以在程序中的其他位置读取它们。 我创建了一个带有一些复选框的新表单:

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;
            }
        }
    }
}

现在我想每次保存一个/任何复选框的状态。 我还使用新表单和form1之间的变量添加了一个类i:

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;
    }
}

现在如何通过将设置保存到文本文件中来在form1中使用它? 例如,在文本文件中,内容将类似于:

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

然后,如果我改变其中一个的状态,它将把它写在文本文件中:

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

在form1 top我添加了

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

然后在构造函数

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

我知道应用程序它自己在属性中有设置但我想这次使用文本文件,因为我有很多设置,我可能会有更多的设置。

或者在我所做的属性中使用应用程序中的设置:

Settings

但是现在我如何在我的程序中使用它来保存新表单中的每个复选框状态,然后在form1中使用它?

3 个答案:

答案 0 :(得分:2)

您可以使用json.net

这样的事情来保存数据

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));
}

您可以像这样阅读

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

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

答案 1 :(得分:1)

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());
}

答案 2 :(得分:1)

建议您在使用.NET框架时使用XML。

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;
    }
}

此外,不要为所有四个复选框创建相同的事件,只需使用1。

单一事件内部:

ckCheckBox1.Checked = !ckCheckBox1.Checked;