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

How to get values from a text file and set them in a Textbox?

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

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

    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);
            }
        }
    }

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

    private void bDirekt_Click(object sender, RoutedEventArgs e)
    {
        using (StreamReader sr = new StreamReader("variables.txt")) ;

        string line = "";
        while ((line = sr.ReadLine()) != null)
        {
            monate2.Text = 
        }

    }

非常感谢您的帮助。

试试这个

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();