Search code examples
c#file-read

Fill Textboxes With Information From .txt File


I have this text in a .txt file

Username:Password
Username2:Password2
Username3:Password3

And i want to set the value of line 2(example) inside the .txt file to the textboxes

This is what i mean:

Textbox1.text = Username2;
Textbox2.text = Password2;

Any links that could provide help are really appreciated, thanks in advance


Solution

  • You can do like this :

    // Reading all lines of files
    var txtLines =  File.ReadAllLines("your_file_path");
    
    // Make sure, there should be atleast more than one line
    // as you want to get username/password from second line
    if(txtLines != null && txtLines.Count() > 1)
    {
        // Skip first line and after that get first line 
        var secondLine = txtLines.ToList().Skip(1).First();
    
        // split it by colon
        var splittedText = secondLine.Split(':');
        if(splittedText.Count() > 1)
        {
            Textbox1.Text = splittedText[0];
            Textbox2.Text = splittedText[1];
        }
    }