Search code examples
c#getsettext-filesstreamreader

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


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.


Solution

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