如何从文本文件中获取值并将其设置在文本框中?

时间:2016-06-28 10:31:46

标签: c# get set text-files streamreader

问题在于:我有两节课。表单1创建一个.txt文件并在其中设置两个值(字符串)。现在我想通过按下按钮(bDirekt)来获取这两个字符串,并在表单2的文本框中设置每个字符串。

表格1(据我所知应该是正确的,但请告诉我,如果我错了):

if not last or np.abs((x[1]-last)/last) > 0.1:

表格2(不知道如何继续):

    public void Txfw()
    {
        string txBetrag = gBetrag.Text;
        string txMonate = gMonate.Text;

        string[] vars = new string[] { txBetrag, txMonate };
        using (StreamWriter sw = new StreamWriter(@"C:\Users\p2\Desktop\variablen.txt"))
        {

            foreach (string s in vars)
            {
                sw.WriteLine(s);
            }
        }
    }

我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

试试这个

StringBuilder sb = new StringBuilder();
    using (StreamReader sr = new StreamReader(@"C:\Users\p2\Desktop\variablen.txt"))
   {
                   string line;

                   // Read and display lines from the file until 
                   // the end of the file is reached. 
                   while ((line = sr.ReadLine()) != null)
                   {
                      sb.Append((line);
                   }
    }
    monate2.Text = sb.Tostring();

更新:要将第一行与其他文本分开,您可以试试这个。总有更好的方法来实现这一目标。

StringBuilder sb = new StringBuilder();
    string headerLine = string.Empty;
    int currentLine = 0;
        using (StreamReader sr = new StreamReader(@"C:\Users\p2\Desktop\variablen.txt"))
       {
                       string line;

                       // Read and display lines from the file until 
                       // the end of the file is reached. 
                       while ((line = sr.ReadLine()) != null)
                       {
                          currentLine++; //increment to keep track of current line number.
                          if(currentLine == 1)
                          {
                            headerLine = line;
                            continue; //skips rest of the processing and goes to next line in while loop
                          }
                          sb.Append((line);

                       }
        }
        header.Text = headerLine;
        monate2.Text = sb.ToString();