读取 .txt,在表单中显示,在表单中编辑并保存

Reading a .txt, Display it in Form, Edit in Form, and Save

我对编程还比较陌生,我设置了一个 "fairly" 简单的任务供我处理。我想要完成的是单击将打开的 Form1 上的 "Settings" 按钮,并将 "config.txt" 的结果 "config.txt" 添加到 Form2 上的标签。

Config.txt 看起来像这样:

[VERSION] 7544
[WIDTH] 480
[HEIGHT] 768
[SCALE] 1
[UI] 8
[SERVER] 2
[DEMO] 1
[BRIGHT] 50
[CURSOR] 1

如果 .txt 文件不存在,我可以使用

创建默认值
using (StreamWriter sw = new StreamWriter("config.txt"))
{
    sw.Write("[DATA1] 7544");
    sw.Write("[DATA2] 8");
    sw.Write("[DATA3] 2");
}

我在单独读取代码行并将它们显示到单独的标签时遇到问题。

int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader(@"config.txt");
while ((line = file.ReadLine()) != null)
{
    //System.Console.WriteLine(line);
    string labelTest = string.Format(line);

    labelVersRead.Text = "Version: " + line;
    counter++;
}    
file.Close();

我认为我遇到的问题是 var line3 = line[3]。我只能让它把完整的.txt输出成一个字符串。

那样的话你可以有一个列表。

var list = new List<Config>();
public class Config{
   string LabelText
   string LabelValue
}

while ((line = file.ReadLine()) != null)
{
    //Split the line based on the pattern and build the list object for Labeltext and LabelValue.

    //You will have to come up with the logic to split the line into string based on the pattern. Where text in the [] is LabelTesxt and anything followed after ] is  LabelValue

    list.Add(new Config{LavelText = "VERSION" ,LabelValue="7544"});

    counter++;
}

//Once done, you could bind the data to the label
var item = list.Find(item => item.LabelText == "VERSION");
lblVersionLabel.Text = item.LabelValue

您似乎总是覆盖标签的 Text

使用 + 附加文本。

labelVersRead.Text += "Version: " + line;

或者在末尾换行

labelVersRead.Text += "Version: " + line + "\r\n";

这是否解决了您遇到的问题?