c# - 如何将键和值写入文本文件并读回?

标签 c# .net winforms

我做了一个新的形式

private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            label1.Text = "Updating Settings File";
            label1.Visible = true;
            w = new StreamWriter(AuthenticationFileName,true);
            w.WriteLine(cTextBox1.Text);
            w.Close();
            timer1.Start();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            button4.Enabled = false;
            label1.Text = "Updating Settings File";
            label1.Visible = true;
            w = new StreamWriter(AuthenticationFileName,true);
            w.WriteLine(cTextBox2.Text);
            w.Close();
            timer1.Start();
        }

然后在 form1 中:

string[] lines = File.ReadAllLines(Authentication.AuthenticationFileName);
apiKey = lines[0];
userid = lines[1];
jsonfiledirectory = lines[2];

但问题是可能存在 apiKey、userid 和 jsonfiledirectory 的顺序与现在不同的情况 [0] [1] [2] 因此,只需让 WriteLine 我想为每一行添加一个键和一个值,例如文本文件将是这样的:

apikey = 435345erfsefs54
userid = myttt@walla.com
jsonfiledirectory = c:\

所以当我读回文本文件时,无论行的顺序如何。

最佳答案

如何使用 Json.Net ( http://www.newtonsoft.com/json),创建一个类来保存您要序列化/反序列化的属性,然后使用 Json.Net 来处理它们?

这很简单,我已经为你做了一个 fiddle :https://dotnetfiddle.net/lkkLUv

基本上创建一个类

public class Settings {
    public string ApiKey { get; set;}
    public string UserId { get; set;}
    public string JsonFileDirectory { get; set;}
}

然后读取它(文件当然需要在json中正确格式化)

Settings settings = JsonConvert.DeserializeObject<Settings>(settingsExample);

其中settingsExample包含从文件中读取的字符串(如果需要,可以使用json直接从文件中读取)

要保存,只需使用JsonConvert.Serialize(settings) 获取字符串并保存到你想要的文件

关于c# - 如何将键和值写入文本文件并读回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34146911/

相关文章:

c# - GUI task.wait 与控制台或线程池的死锁

c# - 为什么我在 XAML 中填充的通用列表在运行时为空?

WinForms 垂直自动调整大小,同时保持宽度可调?

c# - 这段代码在 c# 中的等价物是什么

C#通过传入字段类型来组合方法?

.net - 如何将 DataTable.Select() 的结果绑定(bind)到 ListBox 控件?

c# - 生成的 WSDL 代理具有名为 "System"的类

c# - Infragistics UltraGrid 中复选框的检查更改会引发哪个事件?

c# - 键盘记录程序崩溃

c# - 相对于中心而不是左上角缩放 WPF Canvas