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

时间:2015-05-22 01:08:17

标签: c# file line edit

我对编程比较陌生,而且我已经公平地设置了#34;我工作的简单任务。我想要完成的是点击"设置" 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输出到一个字符串中。

2 个答案:

答案 0 :(得分:0)

在这种情况下,你可以有一个清单。

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

答案 1 :(得分:0)

看起来你总是覆盖标签的inline

使用Text附加文字。

+

或者在最后添加新行

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

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