gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:58 25 4
gpt4 key购买 nike

我做了一个新的形式

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com