-1

here is the problem: I've got two classes. Form 1 creates a .txt-File and sets two values (Strings) in it. Now I want to get these two strings by pressing a button(bDirekt), and set each string in a Textbox in Form 2.

Form 1 (should be correct as far as I know, but please tell me if I'm wrong):

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

Form 2 (got no idea how to go ahead):

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

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

    }

I really appreciate your help.

Seb Dammer
  • 55
  • 8

1 Answers1

0

Try this

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

UPDATE: To separate line one with rest of the text, you can try this. There are always better ways to achieve this.

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();
Vinod
  • 1,882
  • 2
  • 17
  • 27
  • Works perfectly and does almost the thing that I wanted :). But how do I have to change it, so that it copys the first line of the .txt-File in another textbox? Yet it copys both lines in one. – Seb Dammer Jun 28 '16 at 11:24
  • Please see the update I posted – Vinod Jun 28 '16 at 11:41