如何将设置保存到文本文件并读回?

时间:2018-10-06 22:07:46

标签: c# winforms

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

namespace StopwatchTimer
{
    public partial class Form1 : Form
    {
        public string settingsPath = "Settings";

        private string settingsFileName = "settings.txt";
        private static readonly Stopwatch watch = new Stopwatch();
        private long diff = 0, previousTicks = 0, ticksDisplayed = 0;

        public Form1()
        {
            InitializeComponent();

            richTextBox1.TabStop = false;
            richTextBox1.ReadOnly = true;
            richTextBox1.BackColor = Color.White;
            richTextBox1.Cursor = Cursors.Arrow;
            richTextBox1.Enter += RichTextBox1_Enter;

            settingsPath = Path.Combine(Path.GetDirectoryName(Application.LocalUserAppDataPath), settingsPath);
            if (!Directory.Exists(settingsPath))
                Directory.CreateDirectory(settingsPath);

            settingsFileName = Path.Combine(settingsPath, settingsFileName);
            if (!File.Exists(settingsFileName))
                File.Create(settingsFileName);

            string[] settings =  File.ReadAllText(settingsFileName).Split(',');
            if(settings.Length > 0)
            {

            }
    }       radioButton1.Checked = true;
}

我还没有写入文本文件。例如,我想将radioButton1和radioButton2状态写到文本文件中的其他位置,然后在运行应用程序时读回状态。

所以我将Split与','一起使用,但是如何检查回读时的值是属于radioButton1还是radioButton2还是属于textBox或button1?

1 个答案:

答案 0 :(得分:0)

您可以使用内置的winforms设置:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
  Properties.Settings.Default.Username = txtUsername.Text;
  Properties.Settings.Default.Password = txtPassword.Text;
  Properties.Settings.Default.Save();
}

C# Setting load and save

https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-write-user-settings-at-run-time-with-csharp