gpt4 book ai didi

c# - 如何将 Windows 窗体 GUI 中字段的值保存到文件,然后恢复它们?

转载 作者:可可西里 更新时间:2023-11-01 12:00:24 26 4
gpt4 key购买 nike

我想将存储在文件中的内容加载到 WinForms GUI 的字段中。

我现在的方法:我有一个 streamwriter,它将每个文本框写入 .txt 文件中的一行。我有 streamreader 设置,但我不知道如何让它将每一行加载到单独的文本框中。例如:Task1_name(第 1 行)和 task1_desc(第 2 行)需要位于单独的文本框中,我如何才能将其加载到文本框中?

谢谢

代码:

保存按钮:

void Save_buttonClick(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do you want to save?", "Save", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(file);
sw.WriteLine(task1_name.Text);
sw.WriteLine(task1_desc.Text);
sw.WriteLine(task1_date.Value);
sw.WriteLine(task1_check.Checked);
sw.Close();
}
}

加载按钮:

void Load_buttonClick(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do you want to load?", "Load", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamReader sr = new StreamReader(file);
sr.Close();
}
}

最佳答案

使用 XML 序列化。它看起来像这样:

public class MySettings 
{
public String name {get;set;}
public String name {get;set;}
public DateTime date {get;set;}
public bool checked {get;set;}
}

void Save()
{
var s = new MySettings
{
name = this.task1_Name.Text,
desc = this.task1_Desc.Text,
date = this.task1_Date.Value,
checked = this.task1_Check.Checked
};
var ser = new XmlSerializer(typeof(MySettings));
using (var fs = new FileStream(path, FileMode.Create))
{
using (var tw = new StreamWriter(fs, new UTF8Encoding()))
{
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
ser.Serialize(tw, this, ns);
}
}
}

加载它看起来像这样:

    static MySettings Load()
{
var ser = new XmlSerializer(typeof(MySettings));
MySettings settings = null;

try
{
using (var s = File.OpenRead(path))
{
settings = (MySettings) ser.Deserialize(s);
// optionally validate here
}
}
catch (Exception ex1)
{
MessageBox.Show("Cannot read settings. " + ex1.Message,
"error");
settings = null;
}
return settings;
}

然后当然会像这样重置您的表单:

 var settings = Load();
this.task1_Name.Text = settings.name;
this.task1_Desc.Text = settings.desc;
this.task1_Date.Value = settings.date;
this.task1_Check.Checked = settings.checked;

关于c# - 如何将 Windows 窗体 GUI 中字段的值保存到文件,然后恢复它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10542988/

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