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



我对编程比较陌生,我已经为自己设置了一个"相当"简单的任务。我想要完成的是点击Form1上的"设置"按钮,该按钮将打开并将"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 + "rn";

这能解决你遇到的问题吗?

相关内容

  • 没有找到相关文章

最新更新